Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Can it fork?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#define PRINT_ERROR(...) fprintf(stdout, "[ERROR (%i)] ", getpid()); fprintf(stdout, __VA_ARGS__); fprintf(stdout, "\n");
#define PRINT_INFO(...) fprintf(stdout, "[INFO (%i)] ", getpid()); fprintf(stdout, __VA_ARGS__); fprintf(stdout, "\n");
int main(int argc, char *argv[]) {
size_t alloc_step_size_mb = 128;
int n_alloc_steps = 1024;
size_t alloc_step_size = alloc_step_size_mb * 1024 * 1024;
int flags = MAP_PRIVATE | MAP_ANONYMOUS;
if (getenv("ALLOC_NORESERVE") != NULL) {
// Set MAP_NORESERVE, which will result in our VMAs not having
// the VM_ACCOUNT flag set and therefore will allow us to fork
// just as much as we want.
flags |= MAP_NORESERVE;
}
int alloc_addr_offset = alloc_step_size;
if (getenv("ALLOC_SCATTER") != NULL) {
// Add an arbitrary offset to force the kernel to allocate a
// *new* VMA and not merge VMAs when we mmap.
alloc_addr_offset += 2 * alloc_step_size;
}
int ret = 0;
int i = 0;
void* max_mmap_addr = NULL;
void* mmap_addr = NULL;
for(i; i < n_alloc_steps; i++) {
// We'll use the lower-level mmap rather than malloc to
// allocate memory in order to get more control over our memory
// allocation.
if ((mmap_addr = mmap(
max_mmap_addr + alloc_addr_offset,
alloc_step_size,
PROT_READ | PROT_WRITE,
flags,
-1,
0
)) == MAP_FAILED) {
PRINT_ERROR("mmap failed: %s", strerror(errno));
}
if (mmap_addr > max_mmap_addr) {
max_mmap_addr = mmap_addr;
}
int pid = fork();
if (pid < 0) {
PRINT_ERROR("fork failed: %s", strerror(errno));
ret = 1;
break;
} else if (pid == 0) {
// Quit the child immediately
_exit(0);
}
// Wait the child
wait(NULL);
}
if (ret == 0) {
PRINT_INFO("all %d fork iterations succeeded", i);
} else {
PRINT_ERROR("fork failed after %d iterations", i);
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment