os: add linux API for getting cgroup by pid

This commit is contained in:
Mitchell Hashimoto
2024-06-04 15:15:11 -07:00
parent 955246d6a0
commit 0a5f3fa0a4
2 changed files with 29 additions and 0 deletions

28
src/os/linux.zig Normal file
View File

@ -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/<pid>/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);
}

View File

@ -13,6 +13,7 @@ pub usingnamespace @import("open.zig");
pub usingnamespace @import("pipe.zig"); pub usingnamespace @import("pipe.zig");
pub usingnamespace @import("resourcesdir.zig"); pub usingnamespace @import("resourcesdir.zig");
pub const TempDir = @import("TempDir.zig"); pub const TempDir = @import("TempDir.zig");
pub const linux = @import("linux.zig");
pub const passwd = @import("passwd.zig"); pub const passwd = @import("passwd.zig");
pub const xdg = @import("xdg.zig"); pub const xdg = @import("xdg.zig");
pub const windows = @import("windows.zig"); pub const windows = @import("windows.zig");