Created
January 13, 2020 21:11
-
-
Save pinkeen/67299d6dffb5933a177de987053171b5 to your computer and use it in GitHub Desktop.
Small C tool for testing OOM killers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdlib.h> | |
#include<stdio.h> | |
#include<string.h> | |
#include<unistd.h> | |
#include<signal.h> | |
#define MIB_SZ(SZ) ((SZ) / 0x100000) | |
#define PER_SZ(SZ, TOTAL) ((SZ * 100) / (TOTAL)) | |
#ifdef __linux__ | |
#include <linux/sysinfo.h> | |
void print_sysinfo() { | |
struct sysinfo info; | |
sysinfo(&info); | |
printf (" -> Mem free: %u MiB / %lu MiB (%u %%)\n", | |
MIB_SZ(info.freeram), | |
MIB_SZ(info.totalram), | |
PER_SZ(info.freeram, info.totalram) | |
); | |
printf (" -> Swap free: %u MiB / %u MiB (%u %%)\n", | |
MIB_SZ(info.freeswap), | |
MIB_SZ(info.totalswap), | |
PER_SZ(info.freeswap, info.totalswap) | |
); | |
} | |
#else | |
void print_sysinfo() {}; | |
#endif | |
void sig_handler(int signum, siginfo_t *info, void *ptr) { | |
fprintf(stderr, " ! Caugth SIGTERM, ignoring... \n"); | |
} | |
void sig_handler_setup() { | |
static struct sigaction _sigact; | |
memset(&_sigact, 0, sizeof(_sigact)); | |
_sigact.sa_sigaction = sig_handler; | |
_sigact.sa_flags = SA_SIGINFO; | |
sigaction(SIGTERM, &_sigact, NULL); | |
} | |
int main(int argc, char **argv) { | |
size_t alloc_sz = 0; | |
size_t chunk_sz = 0xA00000; | |
size_t **bufs; | |
int delay_ms = 25; | |
int cnt = 200; | |
int idx; | |
if (argc >= 2) { | |
cnt = atoi(argv[1]); | |
} | |
if (argc >= 3) { | |
delay_ms = atoi(argv[2]); | |
} | |
bufs = malloc(sizeof(size_t) * cnt); | |
sig_handler_setup(); | |
printf(" * Will attempt to allocate %u chunks of size %.2f Mib totalling %.2f MiB\n", | |
cnt, | |
MIB_SZ((float)chunk_sz), | |
MIB_SZ((float)chunk_sz * cnt) | |
); | |
printf(" * Total will take %.2f sec with delay of %u ms between allocations\n", | |
delay_ms * cnt / 1000.0, | |
delay_ms | |
); | |
for (idx = 0; idx < cnt; ++idx) { | |
print_sysinfo(); | |
alloc_sz += chunk_sz; | |
printf(" - [%u\\%u] Allocating %.2f MiB chunk totalling %.2f MiB\n", | |
idx, | |
cnt, | |
MIB_SZ((float)chunk_sz), | |
MIB_SZ((float)alloc_sz) | |
); | |
if ((bufs[idx] = malloc(chunk_sz)) == NULL) { | |
fprintf(stderr, " ! malloc() failed - exiting!\n"); | |
exit(9); | |
} | |
memset(bufs[idx], 'x', chunk_sz); | |
usleep(delay_ms * 1E3); | |
} | |
printf(" * Completed full allocation successfully\n"); | |
print_sysinfo(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment