The mmap advantage

Now that we understand how to use the mmap(2) system call, we revisit our earlier discussion: recall, using the read(2)/write(2) or even the SG-I/O type APIs (the [p]readv|writev[2](2)) resulted in a double-copy; memory wastage (plus the fact that CPU caches get trashed as well).

The key to realizing why the mmap(2) so effectively solves this serious issue is this: the mmap(2) sets up a file mapping by internally mapping the kernel page caches pages that contain the file data (that was read in from the storage device) directly into the process virtual address space. This diagram (Figure 3) puts this into perspective (and makes it self-explanatory):

Figure 3: Page cache populated with disk data

A mapping is not a copy; ...

Get Hands-On System Programming with Linux 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.