-
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathcgroup.cpp
More file actions
73 lines (62 loc) · 1.83 KB
/
Copy pathcgroup.cpp
File metadata and controls
73 lines (62 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
namespace cgroup {
static ssize_t fdgets(char *buf, const size_t size, int fd) {
ssize_t len = 0;
buf[0] = '\0';
while (len < size - 1) {
ssize_t ret = read(fd, buf + len, 1);
if (ret < 0)
return -1;
if (ret == 0)
break;
if (buf[len] == '\0' || buf[len++] == '\n') {
break;
}
}
buf[len] = '\0';
buf[size - 1] = '\0';
return len;
}
int get_cgroup(int pid, int *cuid, int *cpid) {
char buf[PATH_MAX];
snprintf(buf, PATH_MAX, "/proc/%d/cgroup", pid);
int fd = open(buf, O_RDONLY);
if (fd == -1)
return -1;
while (fdgets(buf, PATH_MAX, fd) > 0) {
if (sscanf(buf, "%*d:cpuacct:/uid_%d/pid_%d", cuid, cpid) == 2) {
close(fd);
return 0;
}
}
close(fd);
return -1;
}
static int switch_cgroup(int pid, int cuid, int cpid, const char *name) {
char buf[PATH_MAX];
if (cuid != -1 && cpid != -1) {
snprintf(buf, PATH_MAX, "/acct/uid_%d/pid_%d/%s", cuid, cpid, name);
} else {
snprintf(buf, PATH_MAX, "/acct/%s", name);
}
int fd = open(buf, O_WRONLY | O_APPEND);
if (fd == -1)
return -1;
snprintf(buf, PATH_MAX, "%d\n", pid);
if (write(fd, buf, strlen(buf)) == -1) {
close(fd);
return -1;
}
close(fd);
return 0;
}
int switch_cgroup(int pid, int cuid, int cpid) {
int res = 0;
res += switch_cgroup(pid, cuid, cpid, "cgroup.procs");
res += switch_cgroup(pid, cuid, cpid, "tasks");
return res;
}
}