1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Simple memory eater. Runs as a daemon. Prints the child PID to
17 * std so you can easily kill it later.
18 * Usage: memeater <size in MB>
19 */
20
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <fcntl.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27
main(int argc,char * argv[])28 int main(int argc, char *argv[])
29 {
30 pid_t pid;
31 int fd;
32 int numMb = argc > 1 ? atoi(argv[1]) : 1;
33
34 if (argc < 2) {
35 printf("Usage: memeater <num MB to allocate>\n");
36 exit(1);
37 }
38
39 switch (fork()) {
40 case -1:
41 perror(argv[0]);
42 exit(1);
43 break;
44 case 0: /* child */
45 chdir("/");
46 umask(0);
47 setpgrp();
48 setsid();
49 /* fork again to fully detach from controlling terminal. */
50 switch (pid = fork()) {
51 case -1:
52 perror("failed to fork");
53 break;
54 case 0: /* second child */
55 /* redirect to /dev/null */
56 close(0);
57 open("/dev/null", 0);
58 for (fd = 3; fd < 256; fd++) {
59 close(fd);
60 }
61
62 printf("Allocating %d MB\n", numMb);
63 fflush(stdout);
64 /* allocate memory and fill it */
65 while (numMb > 0) {
66 // Allocate 500MB at a time at most
67 int mbToAllocate = numMb > 500 ? 500 : numMb;
68 int bytesToAllocate = mbToAllocate * 1024 * 1024;
69 char *p = malloc(bytesToAllocate);
70 if (p == NULL) {
71 printf("Failed to allocate memory\n");
72 exit(1);
73 }
74 for (int j = 0; j < bytesToAllocate; j++) {
75 p[j] = j & 0xFF;
76 }
77 printf("Allocated %d MB %p\n", mbToAllocate, p);
78 fflush(stdout);
79 numMb -= mbToAllocate;
80 }
81
82 close(1);
83 if (open("/dev/null", O_WRONLY) < 0) {
84 perror("/dev/null");
85 exit(1);
86 }
87 close(2);
88 dup(1);
89
90 /* Sit around doing nothing */
91 while (1) {
92 usleep(1000000);
93 }
94 default:
95 /* so caller can easily kill it later. */
96 printf("%d\n", pid);
97 exit(0);
98 break;
99 }
100 break;
101 default:
102 exit(0);
103 break;
104 }
105 return 0;
106 }
107
108