Memory Mapped Files

In addition to reading and writing files through the use of read() and write(), UNIX supports the ability to map a file into the process' address space and read and write to the file through memory accesses. This allows unrelated processes to access files with either shared or private mappings. Mapped files are also used by the operating system for executable files.

The mmap() system call allows a process to establish a mapping to an already open file:

#include <sys/mman.h>

void mmap(void addr, size_t len, int prot, int flags,
          int fildes, off_t off);

The file is mapped from an offset of off bytes within the file for len bytes. Note that the offset must be on a page size boundary. Thus, if the page size of the system is 4KB, the offset must be 0, 4096, 8192 and so on. The size of the mapping does not need to be a multiple of the page size although the kernel will round the request up to the nearest page size boundary. For example, if off is set to 0 and size is set to 2048, on systems with a 4KB page size, the mapping established will actually be for 4KB.

Figure 3.2 shows the relationship between the pages in the user's address space and how they relate to the file being mapped. The page size of the underlying hardware platform can be determined by making a call to sysconf() as follows:

#include <unistd.h>

main()
{
   printf(“PAGESIZE = %d\n”, sysconf(_SC_PAGESIZE));
}

Typically the page size will be 4KB or 8KB. For example, as expected, when the program is ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.