1 /* Compile with:
2 * i686-pc-linux-gnu-gcc hog.c -o hog
3 */
4
5 #include <fcntl.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12
13 #define MEGA (1 << 20)
14 #define CHUNK_SIZE MEGA /* one-megabyte chunks */
15 #define MAX_CHUNKS 4096
16 const int n_touches = CHUNK_SIZE >> 12; /* average 1 per page */
17 char *chunks[MAX_CHUNKS];
18
19
estrtol(const char * s)20 long int estrtol(const char *s) {
21 char *end;
22 long int n;
23 n = strtol(s, &end, 10);
24 if (*end != '\0') {
25 fprintf(stderr, "hog: malformed integer %s\n", s);
26 exit(1);
27 }
28 return n;
29 }
30
31
main(int ac,const char ** av)32 int main(int ac, const char **av) {
33 int chunk;
34 int compression_factor = 3;
35 unsigned int i, c, x;
36 long int megabytes;
37 int random_fd = open("/dev/urandom", O_RDONLY);
38 char *fake_data = malloc(CHUNK_SIZE);
39 char *p;
40
41 if (ac != 2 && ac != 3) {
42 fprintf(stderr,
43 "usage: hog <megabytes> [<compression factor (default = 3)>]\n");
44 exit(1);
45 }
46
47 megabytes = estrtol(av[1]);
48
49 if (megabytes > MAX_CHUNKS) {
50 fprintf(stderr, "hog: too many megabytes (%ld, max = %d)\n",
51 megabytes, MAX_CHUNKS);
52 }
53
54 if (ac == 3) {
55 compression_factor = estrtol(av[2]);
56 }
57
58 /* Fill fake_data with fake data so that it compresses to roughly the desired
59 * compression factor.
60 */
61 read(random_fd, fake_data, CHUNK_SIZE / compression_factor);
62 /* Fill the rest of the fake data with ones (compresses well). */
63 memset(fake_data + CHUNK_SIZE / compression_factor, 1,
64 CHUNK_SIZE - (CHUNK_SIZE / compression_factor));
65
66 for (chunk = 0; chunk < megabytes; chunk++) {
67 /* Allocate */
68 p = malloc(CHUNK_SIZE);
69
70 if (p == NULL) {
71 printf("hog: out of memory at chunk %d\n", chunk);
72 break;
73 }
74
75 /* Fill allocated memory with fake data */
76 memcpy(p, fake_data, CHUNK_SIZE);
77
78 /* Remember allocated data. */
79 chunks[chunk] = p;
80 }
81
82 printf("hog: idling\n", chunk);
83 while (1)
84 sleep(10);
85 }
86