-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathmap_private.c
More file actions
86 lines (69 loc) · 1.86 KB
/
map_private.c
File metadata and controls
86 lines (69 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
# MAP_PRIVATE
Creates a copy-on-write version of file in memory.
Changes do not reflect on the file.
TODO application? Vs reading everything to memory?
Maybe pages are only put into memory when you try to read them instead of all at once.
*/
#include "common.h"
int main(void) {
char *filepath = TMPFILE();
int fd;
int *map;
const int data = 0;
enum Constexpr { filesize = sizeof(int) };
/* Create a file and write 0 to it. */
{
fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
write(fd, &data, filesize);
close(fd);
}
/* Private write */
{
fd = open(filepath, O_RDONLY, 0);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
map = mmap(NULL, filesize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("mmap");
exit(EXIT_FAILURE);
}
*map = data + 1;
if (munmap(map, filesize) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
/* Read */
{
fd = open(filepath, O_RDONLY, 0);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
map = mmap(0, filesize, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("mmap");
exit(EXIT_FAILURE);
}
/* Did not change! */
assert(*map == data);
if (munmap(map, filesize) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
return EXIT_SUCCESS;
}