From 0a5f3fa0a4eebde09c0a7b37841163d812dff5d0 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 4 Jun 2024 15:15:11 -0700 Subject: [PATCH] os: add linux API for getting cgroup by pid --- src/os/linux.zig | 28 ++++++++++++++++++++++++++++ src/os/main.zig | 1 + 2 files changed, 29 insertions(+) create mode 100644 src/os/linux.zig diff --git a/src/os/linux.zig b/src/os/linux.zig new file mode 100644 index 000000000..e399883dc --- /dev/null +++ b/src/os/linux.zig @@ -0,0 +1,28 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// Returns the path to the cgroup for the given pid. +pub fn cgroupPath(alloc: Allocator, pid: std.os.linux.pid_t) !?[]const u8 { + var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + // Read our cgroup by opening /proc//cgroup and reading the first + // line. The first line will look something like this: + // 0::/user.slice/user-1000.slice/session-1.scope + // The cgroup path is the third field. + const path = try std.fmt.bufPrint(&buf, "/proc/{}/cgroup", .{pid}); + const file = try std.fs.cwd().openFile(path, .{}); + defer file.close(); + + // Read it all into memory -- we don't expect this file to ever be that large. + var buf_reader = std.io.bufferedReader(file.reader()); + const contents = try buf_reader.reader().readAllAlloc( + alloc, + 1 * 1024 * 1024, // 1MB + ); + defer alloc.free(contents); + + // Find the last ':' + const idx = std.mem.lastIndexOfScalar(u8, contents, ':') orelse return null; + const result = std.mem.trimRight(u8, contents[idx + 1 ..], " \r\n"); + return try alloc.dupe(u8, result); +} diff --git a/src/os/main.zig b/src/os/main.zig index 1782601e0..e3c3ef595 100644 --- a/src/os/main.zig +++ b/src/os/main.zig @@ -13,6 +13,7 @@ pub usingnamespace @import("open.zig"); pub usingnamespace @import("pipe.zig"); pub usingnamespace @import("resourcesdir.zig"); pub const TempDir = @import("TempDir.zig"); +pub const linux = @import("linux.zig"); pub const passwd = @import("passwd.zig"); pub const xdg = @import("xdg.zig"); pub const windows = @import("windows.zig");