-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem-eater.c
71 lines (50 loc) · 1.47 KB
/
mem-eater.c
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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// Author J.K. 2008
long getValue(char * what){
char buff[1024];
int fd = open("/proc/meminfo", O_RDONLY);
int ret = read(fd, buff, 1023);
buff[ret>1023 ? 1023: ret] = 0;
char * line = strstr(buff, what);
if (line == 0){
printf("Error %s not found in %s \n", what, buff);
exit(1);
}
line += strlen(what) + 1;
while(line[0] == ' '){
line++;
}
int pos = 0;
while(line[pos] != ' '){
pos++;
}
line[pos] = 0;
close(fd);
return atoi(line);
}
long getFreeRamKB(){
return getValue("\nMemFree:") +getValue("\nCached:") + getValue("\nBuffers:");
}
int preallocate(long long int maxRAMinKB){
long long int currentRAMinKB = getFreeRamKB();
printf ("starting to malloc RAM currently \n %lld KiB => goal %lld KiB\n", currentRAMinKB, maxRAMinKB);
while(currentRAMinKB > maxRAMinKB){
long long int delta = currentRAMinKB - maxRAMinKB;
long long int toMalloc = (delta < 500 ? delta : 500) * 1024;
char * allocP = malloc(toMalloc);
if(allocP == 0){
printf("could not allocate more RAM - retrying - free:%lld \n", currentRAMinKB);
sleep(5);
}else{
memset(allocP, '1', toMalloc);
}
currentRAMinKB = getFreeRamKB();
}
printf ("Finished now \n %lld - %lld\n", currentRAMinKB, maxRAMinKB);
}