cgroup-util: add helpers for opening cgroup by id

This commit is contained in:
Lennart Poettering
2024-04-06 16:08:23 +02:00
parent cb1b813f0d
commit 3b2874952f
5 changed files with 109 additions and 13 deletions
+48 -1
View File
@@ -22,6 +22,7 @@
#include "log.h"
#include "login-util.h"
#include "macro.h"
#include "missing_fs.h"
#include "missing_magic.h"
#include "missing_threads.h"
#include "mkdir.h"
@@ -39,6 +40,38 @@
#include "user-util.h"
#include "xattr-util.h"
int cg_path_open(const char *controller, const char *path) {
_cleanup_free_ char *fs = NULL;
int r;
r = cg_get_path(controller, path, /* item=*/ NULL, &fs);
if (r < 0)
return r;
return RET_NERRNO(open(fs, O_DIRECTORY|O_CLOEXEC));
}
int cg_cgroupid_open(int cgroupfs_fd, uint64_t id) {
_cleanup_close_ int fsfd = -EBADF;
if (cgroupfs_fd < 0) {
fsfd = open("/sys/fs/cgroup", O_CLOEXEC|O_DIRECTORY);
if (fsfd < 0)
return -errno;
cgroupfs_fd = fsfd;
}
cg_file_handle fh = CG_FILE_HANDLE_INIT;
CG_FILE_HANDLE_CGROUPID(fh) = id;
int fd = open_by_handle_at(cgroupfs_fd, &fh.file_handle, O_DIRECTORY|O_CLOEXEC);
if (fd < 0)
return -errno;
return fd;
}
static int cg_enumerate_items(const char *controller, const char *path, FILE **ret, const char *item) {
_cleanup_free_ char *fs = NULL;
FILE *f;
@@ -1404,7 +1437,7 @@ int cg_pid_get_machine_name(pid_t pid, char **ret_machine) {
int cg_path_get_cgroupid(const char *path, uint64_t *ret) {
cg_file_handle fh = CG_FILE_HANDLE_INIT;
int mnt_id = -1;
int mnt_id;
assert(path);
assert(ret);
@@ -1418,6 +1451,20 @@ int cg_path_get_cgroupid(const char *path, uint64_t *ret) {
return 0;
}
int cg_fd_get_cgroupid(int fd, uint64_t *ret) {
cg_file_handle fh = CG_FILE_HANDLE_INIT;
int mnt_id = -1;
assert(fd >= 0);
assert(ret);
if (name_to_handle_at(fd, "", &fh.file_handle, &mnt_id, AT_EMPTY_PATH) < 0)
return -errno;
*ret = CG_FILE_HANDLE_CGROUPID(fh);
return 0;
}
int cg_path_get_session(const char *path, char **ret_session) {
_cleanup_free_ char *unit = NULL;
char *start, *end;