Skip to content
Visual explainer 3h 30m to learn 5 steps

mmap & memory-mapped files

Map files and anonymous memory and choose shared or private mappings.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 30 of 42

In short

mmap maps a file or anonymous memory straight into your address space, so you access it with pointers instead of read and write. Shared file mappings write changes back to the file and are visible to other processes, while private mappings are copy-on-write. Large allocations, shared libraries and many databases rely on mmap.

Explained simply

Normally you read a file by asking the kernel to copy bytes into a buffer. mmap works differently: it makes the file appear inside your memory, as if it were one big array. You just read p[1000] and the kernel brings in that part of the file when you touch it.

Nothing is read when you call mmap. The kernel only notes "this range of addresses shows that file". The first time you touch a page, a page fault loads it. If you never touch most of a huge file, most of it is never read.

Two choices matter. A shared mapping means your writes go into the file and other processes see them. A private mapping means your writes stay with you; the file never changes. You can also map plain memory with no file behind it, called anonymous memory, which is how malloc gets big blocks.

With mprotect you can change what a range of pages allows (read, write, run code, or nothing at all), and with msync you can make sure changes in a shared mapping have reached the disk.

Press Play on a diagram to walk through it one step at a time.

CompareMapping types
MAP_SHARED file
  • Changes written back to the file
  • Visible to other mappers
  • Flush explicitly with msync
  • Used for shared data and databases
MAP_PRIVATE file
  • Copy-on-write; changes stay private
  • The file is never modified
  • Used to load executables and libraries
  • Cheap for read-only scanning
Anonymous
  • Not backed by a file
  • Zero-filled pages
  • Used by malloc for large blocks
  • Shared anonymous memory survives fork
Compareread() versus mmap() for file access
read and write
  • Copies data into your buffer
  • Errors come back as return values
  • Works on pipes, sockets and files
  • Easy to grow and append
mmap
  • No copy: access the page cache directly
  • Errors arrive as SIGBUS
  • Regular files and devices only
  • Great for random access and sharing

In depth

What mmap really sets up

mmap(addr, length, prot, flags, fd, offset) creates one new VMA (a region in your address space) and returns its start. Pass NULL as addr so the kernel picks a free spot. The offset must be a multiple of the page size, and the length is rounded up to whole pages.

The data itself lives in the kernel's page cache, the same cache that read and write use. When you touch a page, the fault handler finds the file page in the cache (or reads it from disk) and points your page table entry straight at it. That is why mmap avoids the extra copy that read makes into your buffer, and why many processes mapping the same file share one copy in RAM.

mmap is not automatically faster. Each first touch of a page costs a fault, and a mapping is harder to grow. For one sequential pass over a file, read with a large buffer is about as fast. mmap shines for random access and for sharing.

SequenceFirst access to a mapped file page
Program
Kernel
Page cache
Disk
  1. 1mmap: create the VMA only
    Program to Kernel: mmap: create the VMA only
  2. 2read p[0]: page fault
    Program to Kernel: read p[0]: page fault
  3. 3is page 0 cached?
    Kernel to Page cache: is page 0 cached?
  4. 4no: read it from disk
    Page cache to Disk: no: read it from disk
  5. 5map the cached page, retry the load
    Kernel to Program: map the cached page, retry the load
  6. 6next accesses: plain memory speed
    Program to Program: next accesses: plain memory speed

MAP_SHARED and MAP_PRIVATE in detail

With MAP_SHARED, your page table points at the page cache page itself. A write changes that page, so another process that calls read on the file sees the new bytes at once, before anything reaches the disk. Writeback flushes dirty pages to disk later, or now if you call msync. To map shared and writable, the file must be opened O_RDWR, or mmap fails with EACCES.

With MAP_PRIVATE, pages start out shared with the cache but are copy-on-write. Your first write to a page gives you a private copy, and the file never changes. This is how the loader maps executables and libraries: every process can patch its own data pages without touching the file. Private writable mappings work even on files opened O_RDONLY.

mmap cannot make a file longer. If you need more room, grow the file first with ftruncate, then map. Touching a mapped page that lies wholly past the end of the file raises SIGBUS, which also happens when another process truncates the file under you.

  • Shared + writable needs the fd opened O_RDWR
  • Grow with ftruncate before mapping the new range
  • SIGBUS: access past end of file or an I/O error

Anonymous mappings

MAP_ANONYMOUS gives memory with no file behind it. Pass fd -1 and offset 0. The pages start out filled with zeros and are only made real on first touch, just like heap memory. glibc malloc uses this for large blocks (128 KiB and up by default), and thread stacks are anonymous mappings too.

MAP_PRIVATE | MAP_ANONYMOUS is private scratch memory. MAP_SHARED | MAP_ANONYMOUS stays shared with children created by fork afterwards, which makes it the simplest way to share memory between a parent and its children; no file and no name are needed. For unrelated processes, use shm_open or memfd_create and map that descriptor instead.

Useful extra flags: MAP_POPULATE faults all pages in at once (avoiding many small faults later), and MAP_NORESERVE asks the kernel not to reserve swap space for the mapping.

  • mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
  • Always compare the result with MAP_FAILED, not NULL
  • munmap(p, len) gives the pages back immediately

mprotect and guard pages

mprotect(addr, len, prot) changes the permissions of pages that are already mapped. addr must be page-aligned; get the size from sysconf(_SC_PAGESIZE). After the change, any access that breaks the new rules raises SIGSEGV.

A guard page is a page set to PROT_NONE next to a buffer. Running off the end of the buffer then crashes at the exact bad instruction instead of silently corrupting the neighbour. glibc puts a guard page below every thread stack for this reason; you can see them as ---p regions in /proc/PID/maps. Debugging allocators like Electric Fence place one after each allocation.

JIT compilers use mprotect for W^X (write xor execute): they write machine code into a PROT_READ | PROT_WRITE page, then switch it to PROT_READ | PROT_EXEC before running it, so a page is never writable and executable at the same time.

FlowA buffer with a guard page
  1. Step 1
    mmap 2 pages

    PROT_READ | PROT_WRITE, anonymous

  2. Step 2
    mprotect page 2

    PROT_NONE: no access at all

  3. Step 3
    Use page 1

    Normal reads and writes

  4. Step 4
    Overflow into page 2

    Fault: SIGSEGV at the bad line

msync, munmap and durability

Writes to a shared file mapping are in the page cache, not on disk. They will be written back eventually, even after munmap or process exit, but a power cut before that loses them. msync(addr, len, MS_SYNC) blocks until the dirty pages in that range are written, which is what you need before telling a user "saved". addr must be page-aligned. On Linux, MS_ASYNC does nothing extra, because the kernel already tracks and schedules dirty pages; only MS_SYNC gives a guarantee. fsync on the file descriptor also flushes them.

Errors behave differently than with write. If the disk fails while a page is being read in, there is no return value to check: the process gets SIGBUS. That, plus the lack of control over when pages are written, is why many database engines prefer read, write and their own buffer cache, while others (LMDB, for example) build everything on mmap.

  • msync(p, len, MS_SYNC) before reporting success
  • Closing the fd does not remove the mapping; munmap does
  • I/O errors on mapped pages arrive as SIGBUS

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Map a file read-only and scan it~40m
  2. 2
    Compare MAP_SHARED and MAP_PRIVATE~40m
  3. 3
    Allocate anonymous memory with mmap~40m
  4. 4
    Change protections with mprotect~40m
  5. 5
    Flush changes with msync~40m

Key points

  • mmap returns MAP_FAILED, not NULL, on error.
  • Lengths are rounded up to whole pages.
  • Touching pages beyond the end of a mapped file can raise SIGBUS.
  • mprotect changes permissions on mapped pages, for example to create guard pages.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
  int fd = open(argv[1], O_RDONLY); struct stat st;
  if (fd < 0 || fstat(fd, &st) < 0 || st.st_size == 0) return 1;
  char *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  if (p == MAP_FAILED) { perror("mmap"); return 1; }
  long lines = 0;
  for (off_t i = 0; i < st.st_size; i++) lines += p[i] == '\n';
  printf("%ld lines\n", lines);
  munmap(p, st.st_size); close(fd); return 0;
}

Count lines by scanning a mapped file like an array: a tiny wc -l.

Edit a file in place with MAP_SHARED

We turn every lowercase letter in a file into uppercase without reading it into a buffer. Step 1: open with O_RDWR, because a shared writable mapping needs write access. Step 2: get the size with fstat and refuse empty files (mmap with length 0 fails with EINVAL). Step 3: map it MAP_SHARED and change bytes through the pointer. Step 4: msync with MS_SYNC so the change is on disk before we say done.

c
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
  struct stat st; int fd = argc > 1 ? open(argv[1], O_RDWR) : -1;
  if (fd < 0 || fstat(fd, &st) < 0 || st.st_size == 0) { perror("open/fstat"); return 1; }
  char *p = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (p == MAP_FAILED) { perror("mmap"); return 1; }
  for (off_t i = 0; i < st.st_size; i++) p[i] = toupper((unsigned char)p[i]);
  if (msync(p, st.st_size, MS_SYNC) < 0) perror("msync");
  munmap(p, st.st_size); close(fd); return 0;
}

Catch a buffer overflow with a guard page

We give a 4096-byte buffer a PROT_NONE neighbour. Step 1: ask for the real page size. Step 2: map two pages of anonymous memory. Step 3: protect the second page. Step 4: write 4096 bytes, which fits. Step 5: write one more byte. The program dies with SIGSEGV exactly on that line, and gdb or a core dump points straight at it.

c
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
  long pg = sysconf(_SC_PAGESIZE);
  char *p = mmap(NULL, 2 * pg, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) { perror("mmap"); return 1; }
  if (mprotect(p + pg, pg, PROT_NONE) < 0) { perror("mprotect"); return 1; }
  memset(p, 'x', pg);               /* fills page 1: fine */
  puts("page 1 ok");
  p[pg] = 'x';                      /* first byte of the guard page: SIGSEGV */
  puts("never printed");
  return 0;
}

Quick reference

  • Check mmap against MAP_FAILED, never NULL
  • Offset must be page-aligned; length is rounded up to whole pages
  • Shared writable file mapping requires the file opened O_RDWR
  • ftruncate(fd, size) first: mmap cannot grow a file
  • Anonymous: MAP_PRIVATE | MAP_ANONYMOUS with fd -1 and offset 0
  • mprotect(p, len, PROT_NONE) makes a guard page; p must be page-aligned
  • msync(p, len, MS_SYNC) waits for disk; on Linux MS_ASYNC adds nothing
  • madvise(p, len, MADV_SEQUENTIAL) hints a front-to-back scan

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You open a file O_RDONLY and call mmap with PROT_READ | PROT_WRITE and MAP_SHARED. What happens?

Question 2

2A process writes to a MAP_PRIVATE mapping of a file. What happens to the file on disk?

Question 3

3You map 8192 bytes of a file that is only 100 bytes long and read byte 5000. What happens?

Question 4

4Why is mmap not always faster than read?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Map a text file read-only and count how many times the letter e appears. Handle empty files and errors.

  2. Exercise 2medium

    Prove the difference between private and shared: map the same file twice, once MAP_PRIVATE and once MAP_SHARED, write X into the first byte of each in turn, and check the file with cat after each step.

  3. Exercise 3hard

    Write an append-only log file of fixed-size records using mmap: grow the file with ftruncate in steps of 1 MiB and remap when full.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is mmap faster than read?
It depends. mmap avoids one copy and is great for random access or many processes sharing a file, but each new page costs a fault. For a single sequential pass, read with a 64 KiB or larger buffer is usually just as fast.
Does closing the file descriptor unmap the file?
No. The mapping keeps its own reference to the file, so you can close the fd right after mmap. The mapping stays until munmap or process exit.
What causes SIGBUS with mmap?
Touching a page that lies past the end of the file (often because someone truncated it), or an I/O error while the kernel reads the page in.
Can I mmap a pipe or a socket?
No. mmap needs something with stable, addressable contents, like a regular file, a shared memory object or certain devices. Pipes and TCP or UDP sockets are streams of bytes, so mmap fails with ENODEV.

Go deeper

ShareXLinkedInWhatsApp