Created
June 13, 2021 20:27
-
-
Save spaskalev/2968f5d181041967122814e6d649dcd5 to your computer and use it in GitHub Desktop.
copy on write example with mmap in the same process
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 <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); | |
} |
Author
spaskalev
commented
Jun 13, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment