-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgroupv2_memlimit.c
More file actions
67 lines (65 loc) · 1.69 KB
/
Copy pathcgroupv2_memlimit.c
File metadata and controls
67 lines (65 loc) · 1.69 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
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
static int write_file(const char *path, const char *s)
{
int fd = open(path, O_WRONLY);
if (fd < 0) return -1;
ssize_t n = write(fd, s, strlen(s));
close(fd);
return n == (ssize_t)strlen(s) ? 0 : -1;
}
int main(int argc, char **argv)
{
#if !defined(__linux__)
fprintf(stderr, "cgroupv2_memlimit is Linux-only");
return 1;
#else
if (argc < 3) {
fprintf(stderr, "usage: %s limit_bytes command [args...]", argv[0]);
return 1;
}
const char *limit = argv[1];
const char *cg_root = "/sys/fs/cgroup";
char cg_path[256];
snprintf(cg_path, sizeof cg_path, "%s/snippet_mem", cg_root);
mkdir(cg_path, 0755);
char memmax[512];
snprintf(memmax, sizeof memmax, "%s/memory.max", cg_path);
if (write_file(memmax, limit) < 0) {
perror("memory.max");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
char procs_path[512];
snprintf(procs_path, sizeof procs_path, "%s/cgroup.procs", cg_path);
char buf[32];
snprintf(buf, sizeof buf, "%d", getpid());
if (write_file(procs_path, buf) < 0) {
perror("cgroup.procs");
_exit(1);
}
execvp(argv[2], &argv[2]);
perror("execvp");
_exit(1);
} else {
int status;
waitpid(pid, &status, 0);
printf("child exited with status %d", status);
return 0;
}
#endif
}