mmap Explained: How Memory-Mapped Files Work
mmap maps a file into a process's address space so it can be read like memory. How memory-mapped files work, when they beat read(), and their pitfalls.
mmap is a system call that maps a file (or an anonymous region) directly into a process’s virtual address space. After the call, the file’s contents appear as an ordinary range of memory: reading a byte at an address reads the file, and on a shared mapping, writing to it eventually writes the file. The operating system loads pages lazily on first touch, so a program can “open” a multi-gigabyte file instantly and only pay for the parts it actually reads.
Reading a file the usual way
The conventional approach is read(). You allocate a buffer, call read(fd, buf, n), and the kernel copies bytes from its page cache — the in-memory cache of recently used file data — into your buffer. Every read is a system call and a copy. For sequential streaming this is fine and often optimal. For random access across a large file, all those calls and copies add up, and you end up writing your own caching layer on top of the kernel’s.
What mmap does differently
With mmap, you skip the user-space buffer entirely. The call looks like this in C:
int fd = open("data.bin", O_RDONLY);
struct stat st;
fstat(fd, &st);
const char *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
// p[0] .. p[st.st_size - 1] now reflect the file
No data is read at this point. The kernel just records that this range of virtual memory is backed by the file. When the program touches p[i] for the first time, the CPU finds no valid mapping in its page tables and raises a page fault. The kernel handles it by locating the right page of the file — loading it from disk into the page cache if it is not already there — and mapping that physical page into the process. The instruction then retries and succeeds.
The crucial detail is that the page your process sees is the page cache page. There is no second copy. Several processes mapping the same file share the same physical memory, which is exactly how the OS loads shared libraries and executables.
Shared vs private mappings
The flags determine what writes do:
MAP_SHARED: writes modify the page cache directly and are eventually written back to the file. Other processes mapping the file see the changes.msync()forces write-back when you need it on disk at a known point.MAP_PRIVATE: writes trigger copy-on-write. The kernel gives your process its own copy of the modified page; the file and other processes are untouched.MAP_ANONYMOUS: no file at all. The region is zero-filled memory, and this is how many allocators obtain large blocks from the OS.
mmap vs read()
read() | mmap | |
|---|---|---|
| Data copies | Page cache to user buffer | None; maps page cache directly |
| Cost per access | System call per read | Page fault on first touch of each page |
| Random access | Requires seeks or pread | Pointer arithmetic |
| Sharing between processes | Each has its own buffer | Same physical pages |
| Error handling | Return codes | Signals (e.g. SIGBUS) on I/O errors |
| Best for | Streaming, sequential, small files | Large files with random or repeated access |
Where mmap shines
Random access over large files. Indexes, lookup tables, and on-disk data structures like B-trees can be navigated with pointers instead of explicit reads. Some databases and search engines rely on mmap for exactly this, letting the OS manage which parts stay in memory.
Read-mostly data shared by many processes. A large model file or dictionary mapped by several worker processes occupies physical memory once.
Zero-parse file formats. If a file’s on-disk layout matches the in-memory layout, mmap lets you use it immediately with no deserialization step. This is the idea behind formats designed to be loaded by mapping rather than parsing.
Fast startup. Mapping a huge file is nearly instant because nothing is read until it is touched.
The pitfalls
mmap is not a free speedup, and several systems have learned this the hard way.
- Page faults are not cheap. Each first touch costs a trap into the kernel. For a sequential scan, a large
read()with readahead can beat a mapping that faults page by page.madvise()hints such as sequential or will-need help, but they are hints. - I/O errors become signals. If the underlying file is truncated, or the disk fails, an access raises
SIGBUSrather than returning an error. Code has to handle that, which is awkward in most languages. - You lose control of eviction. The kernel decides which pages stay resident. A database that needs predictable latency or strict durability ordering may prefer its own buffer pool and explicit I/O, because it knows more about its access pattern than the kernel does. This is one reason many databases pair their own caching with write-ahead logging instead of relying on mmap for writes.
- TLB pressure. Large mappings mean many page table entries. Random access across them can thrash the TLB, the CPU’s cache of address translations. Huge pages reduce this at the cost of coarser granularity.
- Address space limits. On 64-bit systems this is rarely an issue, but on 32-bit systems you cannot map a file larger than the available address space.
- Concurrent modification. If another process changes or truncates the file while you are reading it through a mapping, you see the change, possibly mid-structure.
mmap beyond C
Most languages expose mmap: Python has the mmap module, Java has MappedByteBuffer through FileChannel.map, Go and Rust have widely used packages and crates, and Node.js reaches it through native addons. Higher-level runtimes may also use it internally for loading code and data. The trade-offs above apply regardless of language; a mapped region is still backed by the same kernel machinery.
The takeaway
mmap turns a file into memory by letting the kernel map page cache pages straight into your address space, loading them on demand through page faults. It eliminates copies, makes random access as simple as pointer arithmetic, and lets processes share one physical copy of data. In exchange you give up explicit control over I/O, error handling, and eviction. Use it for large, read-heavy files with random or shared access; prefer plain read() for streaming and for anything where you need tight control over latency and durability.
Keep reading
The Lycoris Team · · 5 min read Process vs Thread: What's the Difference?
A process is a running program with its own memory; a thread is an execution path inside it that shares that memory. How they differ and when to use each.
Chisato · · 6 min read epoll vs io_uring: Linux Async I/O Models Compared
epoll tells you when a file descriptor is ready; io_uring lets you submit the I/O itself and collect results later. How each works and when to use which.
The Lycoris Team · · 5 min read What Is Little's Law? Capacity Planning Explained
Little's Law relates the number of requests in a system, their arrival rate, and how long each one takes — a simple formula for sizing capacity.