$ uname -rv
4.19.0-16-amd64 #1 SMP Debian 4.19.181-1 (2021-03-19)
$ gcc -o multimap -Wall -Werror multimap.c
$ ./multimap data.txt
Initial m[0] data: "0123456789ABCDEF"
Initial m[1] data: "0123456789ABCDEF"
Final m[0] data: "MODIFIED DATA!!!"
Final m[1] data: "0123456789ABCDEF"
Created
April 2, 2021 22:03
-
-
Save JonathonReinhart/0f0c4c87fa83122b969d9f0a69e3c1b9 to your computer and use it in GitHub Desktop.
Are multiple MAP_PRIVATE mappings of the same file, in the same process, still private?
This file contains 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
0123456789ABCDEF |
This file contains 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
/** | |
* Answering the question: | |
* "Are multiple MAP_PRIVATE mappings of the same file, in the same process, | |
* still private?" | |
* https://stackoverflow.com/q/66925360/119527 | |
*/ | |
#include <errno.h> | |
#include <error.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
static void *map_file(int fd, size_t size) | |
{ | |
void *m; | |
m = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); | |
if (m == MAP_FAILED) | |
error(3, errno, "Failed to mmap fd %d\n", fd); | |
return m; | |
} | |
int main(int argc, char **argv) | |
{ | |
const int nprint = 16; | |
static const char replace[] = "MODIFIED DATA!!!"; | |
const char *path; | |
int fd; | |
struct stat statbuf; | |
size_t sz; | |
void *m[2]; | |
int i; | |
if (argc < 2) | |
error(1, 0, "Usage: multimap PATH"); | |
path = argv[1]; | |
fd = open(path, O_RDONLY); | |
if (fd < 0) | |
error(2, errno, "Failed to open %s\n", path); | |
if (fstat(fd, &statbuf) < 0) | |
error(3, errno, "Failed to stat fd %d\n", fd); | |
sz = statbuf.st_size; | |
if (sz < nprint) | |
error(4, 0, "Data too small"); | |
for (i = 0; i < 2; i++) { | |
m[i] = map_file(fd, sz); | |
printf("Initial m[%d] data: \"%.*s\"\n", i, nprint, (char*)m[i]); | |
} | |
memcpy(m[0], replace, sizeof(replace)); | |
for (i = 0; i < 2; i++) { | |
printf("Final m[%d] data: \"%.*s\"\n", i, nprint, (char*)m[i]); | |
munmap(m[i], sz); | |
} | |
close(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment