Memory Mappings 1025
Although the executable text segment is normally protected to allow only read
and execute access (PROT_READ | PROT_EXEC), it is mapped using MAP_PRIVATE
rather than MAP_SHARED, because a debugger or a self-modifying program can
modify the program text (after first changing the protection on the memory),
and such changes should not be carried through to the underlying file or affect
other processes.
z To map the initialized data segment of an executable or shared library. Such
mappings are made private so that modifications to the contents of the
mapped data segment are not carried through to the underlying file.
Both of these uses of mmap() are normally invisible to a program, because these
mappings are created by the program loader and dynamic linker. Examples of both
kinds of mappings can be seen in the /proc/PID/maps output shown in Section 48.5.
One other, less frequent, use of a private file mapping is to simplify the file-
input logic of a program. This is similar to the use of shared file mappings for
memory-mapped I/O (described in the next section), but allows only for file input.
Figure 49-1: Overview of memory-mapped file
49.4.2 Shared File Mappings
When multiple processes create shared mappings of the same file region, they all
share the same physical pages of memory. In addition, modifications to the contents
of the mapping are carried through to the file. In effect, the file is being treated as
the paging store for this region of memory, as shown in Figure 49-2. (We simplify
things in this diagram by omitting to show that the mapped pages are typically not
contiguous in physical memory.)
Shared file mappings serve two purposes: memory-mapped I/O and IPC. We
consider each of these uses below.
Process virtual
memory
address
returned
by mmap()
mapped
region
mapped
region
offset length
Open file (fd)
increasing
memory address