The Linux Programming Interface

(nextflipdebug5) #1

1026 Chapter 49


Figure 49-2: Two processes with a shared mapping of the same region of a file

Memory-mapped I/O
Since the contents of the shared file mapping are initialized from the file, and any
modifications to the contents of the mapping are automatically carried through to
the file, we can perform file I/O simply by accessing bytes of memory, relying on the
kernel to ensure that the changes to memory are propagated to the mapped file.
(Typically, a program would define a structured data type that corresponds to the
contents of the disk file, and then use that data type to cast the contents of the
mapping.) This technique is referred to as memory-mapped I/O, and is an alternative
to using read() and write() to access the contents of a file.
Memory-mapped I/O has two potential advantages:

z By replacing read() and write() system calls with memory accesses, it can simplify
the logic of some applications.
z It can, in some circumstances, provide better performance than file I/O carried
out using the conventional I/O system calls.

The reasons that memory-mapped I/O can provide performance benefits are as
follows:

z A normal read() or write() involves two transfers: one between the file and the
kernel buffer cache, and the other between the buffer cache and a user-space
buffer. Using mmap() eliminates the second of these transfers. For input, the
data is available to the user process as soon as the kernel has mapped the

Process A
page table

PT entries
for mapped
region

Process B
page table

PT entries
for mapped
region

Mapped
pages

Physical
memory

Mapped
region of
file

Open file

I/O managed

by kernel
Free download pdf