38
• Line 84: We map the file into the application’s address space to allow
our program to access the contents as if in memory. In the second
parameter, we pass the length of the file, requesting Linux to initialize
memory with the full file. We also map the file with both READ and
WRITE access and also as SHARED allowing other processes to map
the same file.
• Line 91: We retire the file descriptor which is no longer needed once
a file is mapped.
• Line 94: We write data into the file by accessing it like memory
through the pointer returned by mmap.
• Line 101: We explicitly flush the newly written string to the backing
storage device.
Listing 3-2 shows an example of C code that memory maps a file, writes data into
the file, and then uses the FlushViewOfFile() and FlushFileBuffers() system calls to
flush the modified data to the file on the storage device.
Listing 3-2. Memory-mapped file on Windows example
45 #include
46 #include
47 #include
48 #include
49 #include
50 #include
51 #include
52
53 int
54 main(int argc, char *argv[])
55 {
56
if (argc != 2) {
57
fprintf(stderr, "Usage: %s filename\n",
58
argv[0]);
59
exit(1);
60
}
61
Chapter 3 Operating SyStem SuppOrt fOr perSiStent memOry
• Line 84: We map the file into the application’s address space to allow
our program to access the contents as if in memory. In the second
parameter, we pass the length of the file, requesting Linux to initialize
memory with the full file. We also map the file with both READ and
WRITE access and also as SHARED allowing other processes to map
the same file.
• Line 91: We retire the file descriptor which is no longer needed once
a file is mapped.
• Line 94: We write data into the file by accessing it like memory
through the pointer returned by mmap.
• Line 101: We explicitly flush the newly written string to the backing
storage device.
Listing 3-2 shows an example of C code that memory maps a file, writes data into
the file, and then uses the FlushViewOfFile() and FlushFileBuffers() system calls to
flush the modified data to the file on the storage device.
Listing 3-2. Memory-mapped file on Windows example
45 #include
46 #include
47 #include
48 #include
49 #include
50 #include
51 #include
52
53 int
54 main(int argc, char *argv[])
55 {
56
if (argc != 2) {
57
fprintf(stderr, "Usage: %s filename\n",
58
argv[0]);
59
exit(1);
60
}
61
Chapter 3 Operating SyStem SuppOrt fOr perSiStent memOry
