Skip to content

Instantly share code, notes, and snippets.

@crquan
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crquan/326bde37e1ddda8effe5 to your computer and use it in GitHub Desktop.
Save crquan/326bde37e1ddda8effe5 to your computer and use it in GitHub Desktop.
the remap testing program by a loop calling mremap memory increasing one page size
// the remap testing program by a loop calling mremap memory increasing one page size
// till it failed, or be killed by OOM
// Compile by: gcc -Wall -D_GNU_SOURCE -o remap remap.c
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(void)
{
const int PAGE_SIZE = sysconf(_SC_PAGESIZE);
size_t mmap_sz = PAGE_SIZE;
char *pp = mmap(NULL, mmap_sz, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (pp == MAP_FAILED) {
int saved = errno;
perror("\nmremap failed");
fprintf(stderr, "remap failed %s (%d).\n",
strerror(saved), saved);
return 1;
}
pp[mmap_sz-1] = '\0';
printf("allocated one page @%p, (PAGE_SIZE: %d)\n",
pp, PAGE_SIZE);
while (1) {
char *new_pp = mremap(pp, mmap_sz, mmap_sz+PAGE_SIZE, MREMAP_MAYMOVE);
if (new_pp == MAP_FAILED) {
int saved = errno;
perror("\nmremap failed");
fprintf(stderr, "remap failed %s (%d).\n",
strerror(saved), saved);
return 1;
}
if (new_pp != pp) {
printf("\n");
pp = new_pp;
}
mmap_sz += PAGE_SIZE;
pp[mmap_sz-1] = '\0';
printf("\rgrabbed %lu bytes of memory (%lu pages) @ %0*lx.",
mmap_sz, mmap_sz / PAGE_SIZE,
(int)sizeof(long)*2, (long)pp);
fflush(stdout);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment