Skip to content

Instantly share code, notes, and snippets.

@kiryl
Created April 17, 2015 05:26
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 kiryl/3ecef25fdb9355d2eca7 to your computer and use it in GitHub Desktop.
Save kiryl/3ecef25fdb9355d2eca7 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
char *p;
int fd;
/* Create a file and populate first page of page cache */
fd = open("/tmp", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
write(fd, "1", 1);
/* Create a *read-only* *private* mapping of the file */
p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
/*
* Since the mapping is read-only, mlock() will populate the mapping
* with PTEs pointing to page cache without triggering COW.
*/
mlock(p, 4096);
/*
* Mapping became read-write, but it's still populated with PTEs
* pointing to page cache.
*/
mprotect(p, 4096, PROT_READ | PROT_WRITE);
/* Trigger COW: major fault in mlock()ed VMA. */
*p = 1;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment