-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmap.c
113 lines (95 loc) · 2.58 KB
/
mmap.c
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // getpagesize(), ftruncate()
#include <sys/types.h> // mmap()
#include <sys/mman.h> // mmap()
#include <string.h> // memcpy()
#include <math.h> // pow()
struct TestData {
size_t a;
size_t b;
};
void ppData(struct TestData * testData)
{
printf("TestData {\n");
fprintf(stdout, "a: %zu, b: %zu\n", testData->a, testData->b);
printf("}\n");
}
struct TestData * writeTestData(size_t a, size_t b)
{
fprintf(stdout, "========== pagesize: %d\n", getpagesize());
printf("========== writing\n");
FILE * fp;
if ((fp = fopen("./mmaptestfile", "w+")) == 0) {
perror("open");
exit(1);
}
int fd = fileno(fp);
if ((ftruncate(fd, sizeof (struct TestData))) == -1) {
perror("ftruncate");
close(fd);
exit(1);
}
char * data;
data = mmap(0, sizeof (struct TestData), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
fprintf(stdout, "mmap addr: %p\n", data);
if (data == (void *)-1) {
perror("mmap");
close(fd);
exit(1);
}
struct TestData testStruct = {a,b};
memcpy(data, &testStruct, sizeof (struct TestData));
msync((void *) data, sizeof (struct TestData), MS_SYNC);
printf("========== initial values\n");
ppData ((struct TestData *) data);
fclose(fp);
return (struct TestData *) data;
}
struct TestData * readAndOverwrite(size_t newA, size_t newB, const char * fopen_mode)
{
FILE * fp;
if ((fp = fopen("./mmaptestfile", fopen_mode)) == 0) {
perror("open");
exit(1);
}
int fd = fileno(fp);
if ((ftruncate(fd, sizeof (struct TestData))) == -1) {
perror("ftruncate");
close(fd);
exit(1);
}
struct TestData * testData;
testData = mmap(0, sizeof (struct TestData), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
fclose(fp);
if (testData == (void *)-1) {
perror("mmap");
close(fd);
exit(1);
}
fprintf(stdout, "mmap addr: %p\n", testData);
testData->a = newA;
testData->b = newB;
printf("========== local change\n");
ppData (testData);
return testData;
}
int main(void)
{
printf("========== start\n");
struct TestData * originalMmap = writeTestData(33, 69);
struct TestData * secondMmap = readAndOverwrite(1, 2, "r+"); // simulate read
printf("========== read second mapping\n");
ppData (secondMmap);
struct TestData * thirdMmap = readAndOverwrite(3, 4, "w+"); // simulate truncate
printf("========== read third mapping\n");
ppData (thirdMmap);
printf("========== re-read original mapping\n");
ppData (originalMmap);
printf("========== re-read second mapping\n");
ppData (secondMmap);
printf("========== re-read third mapping\n");
ppData (thirdMmap);
printf("========== end\n");
exit(EXIT_SUCCESS);
}