Created
March 26, 2012 12:10
-
-
Save jfairbairn/2204691 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdint.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <sys/mman.h> | |
#include <sys/user.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <assert.h> | |
/* We're mmapping 10GB of data (privately, COW-style), | |
* then getting another 10GB after that for extra writes. | |
* To make this work, we have to actually tell the first | |
* mmap() call that we want the full amount of memory in a | |
* contiguous block, then munmap() the latter region. | |
* Then we "reallocate" this as a MAP_FIXED|MAP_ANONYMOUS | |
* region instead. Profit! | |
*/ | |
int main() { | |
int fd = open("10GB", O_RDWR|O_APPEND); | |
const size_t sz = 10 * (uint64_t)1024 * (uint64_t)1024 * (uint64_t)1024; | |
void *mem = mmap(NULL, sz*2, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); | |
munmap(mem+sz, sz); | |
void *mem2 = mmap(mem+sz, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0); | |
if ((int64_t) mem == -1) { | |
fprintf(stderr, "ouch: %s\n", strerror(errno)); | |
exit(255); | |
} | |
if ((int64_t) mem2 == -1) { | |
fprintf(stderr, "ouch2: %s\n", strerror(errno)); | |
exit(255); | |
} | |
assert(mem2 == mem+sz); | |
sprintf((char *)(mem+sz), "hello mike\n"); | |
munmap(mem,sz); | |
munmap(mem2, sz); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment