Specifying MAP_FIXED
in the mmap() flags argument forces the kernel to interpret the address in addr exactly, rather than take it as a hint. If we specify MAP_FIXED
, addr must be page-aligned.
Generally, a portable application should omit the use of MAP_FIXED
, and specify addr as NULL
, which allows the system to choose the address at which to place the mapping. The reasons for this are the same as those that we outlined in Using Shared Memory when explaining why it usually preferable to specify shmaddr as NULL
when attaching a System V shared memory segment using shmat().
There is, however, one situation where a portable application might use MAP_FIXED
. If MAP_FIXED
is specified when calling mmap(), and the memory region beginning at addr and running for length bytes overlaps the pages of any previous mapping, then the overlapped pages are replaced by the new mapping. We can use this feature to portably map multiple parts of a file (or files) into a contiguous region of memory, as follows:
Use mmap() to create an anonymous mapping (Anonymous Mappings). In the mmap() call, we specify addr as NULL
and don’t specify the MAP_FIXED
flag. This allows the kernel to choose an address for the mapping.
Use a series of mmap() calls specifying MAP_FIXED
to map (i.e., overlay) file regions into different parts of the mapping created in the preceding step.
Although we could skip the first step, and use a series of mmap() MAP_FIXED
operations to create a set of contiguous mappings at an address range selected by the application, this approach is less portable than performing both steps. As noted above, a portable application should avoid trying to create a new mapping at a fixed address. The first step avoids the portability problem, because we let the kernel select a contiguous address range, and then create new mappings within that address range.
From Linux 2.6 onward, the remap_file_pages() system call, which we describe in the next section, can also be used to achieve the same effect. However, the use of MAP_FIXED
is more portable than remap_file_pages(), which is Linux-specific.