11 void (*cgroup_perror
)(const char *s
) = perror
;
12 static const char cgroupfs
[] = "/sys/fs/cgroup/";
15 cgroup_setup(const char *chier
, const char *controllers
)
17 char chierdir
[PATH_MAX
];
18 snprintf(chierdir
, sizeof(chierdir
), "%s%s", cgroupfs
, chier
);
19 if (access(chierdir
, F_OK
) >= 0)
22 if (mount("none", cgroupfs
, "tmpfs", 0, NULL
) < 0) {
23 cgroup_perror(cgroupfs
);
26 if (mkdir(chierdir
, 0777) < 0) {
27 cgroup_perror(chierdir
);
30 if (mount("none", chierdir
, "cgroup", 0, controllers
) < 0) {
31 cgroup_perror(chierdir
);
38 cgroup_create(const char *chier
, const char *cgroup
)
40 char cgroupdir
[PATH_MAX
];
41 snprintf(cgroupdir
, sizeof(cgroupdir
), "%s%s/%s", cgroupfs
, chier
, cgroup
);
42 if (access(cgroupdir
, F_OK
) >= 0)
44 if (mkdir(cgroupdir
, 0777) < 0) {
45 cgroup_perror(cgroupdir
);
53 cgroup_add_task(const char *chier
, const char *cgroup
, pid_t pid
)
55 char tasksfile
[PATH_MAX
];
56 snprintf(tasksfile
, sizeof(tasksfile
), "%s%s/%s/tasks", cgroupfs
, chier
, cgroup
);
57 FILE *tasks
= fopen(tasksfile
, "a");
59 cgroup_perror(tasksfile
);
62 fprintf(tasks
, "%d\n", pid
);
68 cgroup_is_task_in_cgroup(const char *chier
, const char *cgroup
, pid_t pid
)
70 char tasksfile
[PATH_MAX
];
71 snprintf(tasksfile
, sizeof(tasksfile
), "%s%s/%s/tasks", cgroupfs
, chier
, cgroup
);
72 FILE *tasks
= fopen(tasksfile
, "r");
74 cgroup_perror(tasksfile
);
80 while (fgets(line
, sizeof(line
), tasks
)) {
81 if (atoi(line
) == pid
) {
91 cgroup_task_list(const char *chier
, const char *cgroup
, pid_t
**tasklist
)
93 char tasksfile
[PATH_MAX
];
94 snprintf(tasksfile
, sizeof(tasksfile
), "%s%s/%s/tasks", cgroupfs
, chier
, cgroup
);
95 FILE *tasks
= fopen(tasksfile
, "r");
97 cgroup_perror(tasksfile
);
104 while (fgets(line
, sizeof(line
), tasks
)) {
106 *tasklist
= realloc(*tasklist
, (ntasks
+ 32) * sizeof(*tasklist
));
107 (*tasklist
)[ntasks
++] = atoi(line
);
115 cgroup_get_mem_limit(const char *chier
, const char *cgroup
)
117 char limitfile
[PATH_MAX
];
118 snprintf(limitfile
, sizeof(limitfile
), "%s%s/%s/memory.limit_in_bytes", cgroupfs
, chier
, cgroup
);
119 FILE *limit
= fopen(limitfile
, "r");
121 cgroup_perror(limitfile
);
125 fscanf(limit
, "%zu", &nlimit
);
131 cgroup_set_mem_limit(const char *chier
, const char *cgroup
, size_t nlimit
)
133 char limitfile
[PATH_MAX
];
134 snprintf(limitfile
, sizeof(limitfile
), "%s%s/%s/memory.limit_in_bytes", cgroupfs
, chier
, cgroup
);
135 FILE *limit
= fopen(limitfile
, "w");
137 cgroup_perror(limitfile
);
140 fprintf(limit
, "%zu\n", nlimit
);
146 cgroup_get_mem_usage(const char *chier
, const char *cgroup
)
148 char usagefile
[PATH_MAX
];
149 snprintf(usagefile
, sizeof(usagefile
), "%s%s/%s/memory.usage_in_bytes", cgroupfs
, chier
, cgroup
);
150 FILE *usage
= fopen(usagefile
, "r");
152 cgroup_perror(usagefile
);
156 fscanf(usage
, "%zu", &nusage
);