Part 3 of 7 · 2 min read
Shared and private
A mapping is either shared (MAP_SHARED) or private (MAP_PRIVATE). They differ in what happens on a write.
- With
MAP_SHARED, a write changes the page of the file itself. Every process that maps the file sees it, and it is eventually written to the file. - With
MAP_PRIVATE, a write triggers copy-on-write (page 6 of Level 6). The process gets its own copy of the page and changes that. The file and the other processes never see the change.
A test on a 5,000-byte file shows both:
| Action | Result |
|---|---|
Write 'Z' to byte 0 of a MAP_SHARED mapping, then read the file with pread |
the file byte is Z |
Write 'Q' to byte 1 of a MAP_PRIVATE mapping, then read the file with pread |
the file byte is still a, and the mapping shows Q |
| Map with an offset of 100 | the call fails with "Invalid argument" |
The third row shows the rule about offsets: it must be a multiple of the page size (4,096).
In plain words: A shared write reaches the file in two steps. First, it changes a page in memory, which is marked dirty. Later, the kernel writes the dirty page to disk, in the background. A program that needs the data on disk at a certain moment calls msync(addr, length, MS_SYNC), or fsync on the file. Without it, a power failure may lose recent changes. A private mapping is used for data that the process reads and perhaps changes locally, such as the code and the initial data of a program.
Shared and private mapping
A shared mapping (MAP_SHARED) makes writes go to the underlying file or memory object and become visible to every process that maps it, while a private mapping (MAP_PRIVATE) gives a write a private copy of the page by copy-on-write, so that others never see it.
Example: writing 'Z' through a shared mapping changed the file, and writing 'Q' through a private mapping left it unchanged.
Common mistake
A program that maps a file with MAP_PRIVATE and writes to it expecting the file to change will lose its work without any error. Use MAP_SHARED (and PROT_WRITE, with a file opened O_RDWR) for changes that must reach the file.
Check yourself:
1. What does a write do in a MAP_PRIVATE mapping?
2. When should a program call msync?
3. Why must the offset be a multiple of the page size?