Skip to content

Instantly share code, notes, and snippets.

@spaskalev
Created June 13, 2021 20:27
Show Gist options
  • Save spaskalev/2968f5d181041967122814e6d649dcd5 to your computer and use it in GitHub Desktop.
Save spaskalev/2968f5d181041967122814e6d649dcd5 to your computer and use it in GitHub Desktop.
copy on write example with mmap in the same process
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *hello = "Hello world!\n";
int fd = memfd_create("test", 0);
if (ftruncate(fd, 4096)) {
printf("Failure to truncate in-memory file.\n");
exit(-1);
}
int prot_flags = PROT_READ | PROT_WRITE;
void *shared = mmap(NULL, 4096, prot_flags, MAP_SHARED, fd, 0);
if (shared == MAP_FAILED) {
printf("Shared mapping failed.\n");
exit(-1);
}
strncpy(shared, hello, 64);
void *private = mmap(NULL, 4096, prot_flags, MAP_PRIVATE, fd, 0);
if (private == MAP_FAILED) {
printf("Private mapping failed.\n");
exit(-1);
}
printf(shared);
printf(private);
strncpy(shared, "Hello to you too, shared!\n", 64);
printf(shared);
printf(private);
strncpy(private, "Hello to you too, cow!\n", 64);
printf(shared);
printf(private);
}
@spaskalev
Copy link
Author

Compile with -D_GNU_SOURCE to have memfd_create defined

@spaskalev
Copy link
Author

spaskalev commented Jun 13, 2021

$ gcc -D_GNU_SOURCE main.c && ./a.out
Hello world!
Hello world!
Hello to you too, shared!
Hello to you too, shared!
Hello to you too, shared!
Hello to you too, cow!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment