1 #include <errno.h>
2 #include <fcntl.h>
3 #include <getopt.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/mman.h>
8 #include <sys/wait.h>
9 #include <unistd.h>
10
alloc_set(size_t size)11 void *alloc_set(size_t size) {
12 void *addr = NULL;
13
14 addr = malloc(size);
15 if (!addr) {
16 printf("Allocating %zd MB failed\n", size / 1024 / 1024);
17 } else {
18 memset(addr, 0, size);
19 }
20 return addr;
21 }
22
add_pressure(size_t * shared,size_t size,size_t step_size,size_t duration,const char * oom_score)23 void add_pressure(size_t *shared, size_t size, size_t step_size,
24 size_t duration, const char *oom_score) {
25 int fd, ret;
26
27 fd = open("/proc/self/oom_score_adj", O_WRONLY);
28 ret = write(fd, oom_score, strlen(oom_score));
29 if (ret < 0) {
30 printf("Writing oom_score_adj failed with err %s\n",
31 strerror(errno));
32 }
33 close(fd);
34
35 if (alloc_set(size)) {
36 *shared = size;
37 }
38
39 while (alloc_set(step_size)) {
40 size += step_size;
41 *shared = size;
42 usleep(duration);
43 }
44 }
45
usage()46 void usage()
47 {
48 printf("Usage: [OPTIONS]\n\n"
49 " -d N: Duration in microsecond to sleep between each allocation.\n"
50 " -i N: Number of iterations to run the alloc process.\n"
51 " -o N: The oom_score to set the child process to before alloc.\n"
52 " -s N: Number of bytes to allocate in an alloc process loop.\n"
53 );
54 }
55
main(int argc,char * argv[])56 int main(int argc, char *argv[])
57 {
58 pid_t pid;
59 size_t *shared;
60 int c, i = 0;
61
62 size_t duration = 1000;
63 int iterations = 0;
64 const char *oom_score = "899";
65 size_t step_size = 2 * 1024 * 1024; // 2 MB
66 size_t size = step_size;
67
68 while ((c = getopt(argc, argv, "hi:d:o:s:")) != -1) {
69 switch (c)
70 {
71 case 'i':
72 iterations = atoi(optarg);
73 break;
74 case 'd':
75 duration = atoi(optarg);
76 break;
77 case 'o':
78 oom_score = optarg;
79 break;
80 case 's':
81 step_size = atoi(optarg);
82 break;
83 case 'h':
84 usage();
85 abort();
86 default:
87 abort();
88 }
89 }
90
91 shared = (size_t *)mmap(NULL, sizeof(size_t), PROT_READ | PROT_WRITE,
92 MAP_ANONYMOUS | MAP_SHARED, 0, 0);
93
94 while (iterations == 0 || i < iterations) {
95 *shared = 0;
96 pid = fork();
97 if (!pid) {
98 /* Child */
99 add_pressure(shared, size, step_size, duration, oom_score);
100 /* Shoud not get here */
101 exit(0);
102 } else {
103 wait(NULL);
104 printf("Child %d allocated %zd MB\n", i,
105 *shared / 1024 / 1024);
106 size = *shared / 2;
107 }
108 i++;
109 }
110 }
111