Memory-Mapped Files

mmap() is one of the most powerful and widely-used system calls in Linux. It maps a file (or anonymous memory) directly into your process's address space, so you can read and write files using simple pointer operations instead of read()/write() system calls.

What mmap Does

How is mmap different from reading a file normally? With read(), data is copied: disk → kernel page cache → your buffer. With mmap(), the file's pages in the page cache are mapped directly into your virtual address space. No extra copy. You access file data like regular memory — dereference a pointer, get file content.
Normal read: pread(fd, buf, size, offset) → copies data to buf mmap: ptr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, offset) data = ptr[42] → page fault on first access → kernel reads page from disk into page cache → maps that page into your address space → subsequent accesses: direct memory access, no syscall

Private vs Shared Mappings

MAP_SHAREDMAP_PRIVATE
Writes visible to other processes?Yes — immediatelyNo — copy-on-write
Writes go to file?YesNo
Use caseIPC, shared memory, database buffersLoading executables, private scratch space
How do shared libraries work with mmap? When 100 processes use libc.so, the kernel maps the same physical pages into all 100 processes using MAP_SHARED. One physical copy, 100 virtual mappings. This is why shared libraries save enormous amounts of RAM compared to statically linking everything.

Key Use Cases

  • Shared libraries: .so files loaded via mmap — one physical copy, shared by all processes
  • Executable loading: The kernel mmaps your program's binary into memory
  • Large file processing: Databases, search engines — process huge files without reading them all into RAM
  • IPC: Two processes mmap the same file with MAP_SHARED to communicate
  • Anonymous mmap: malloc() uses anonymous mmap (no backing file) for large allocations

Inspecting mmaps

# Every mmap in your shell: cat /proc/self/maps # 7f1234000000-7f1238000000 r-xp 00000000 08:01 789 /lib/x86_64-linux-gnu/libc.so.6 # 7fff12300000-7fff12321000 rw-p 00000000 00:00 0 [stack] # 7fff123ff000-7fff12400000 r-xp 00000000 00:00 0 [vdso] # Columns: address range, permissions, offset, device, inode, name # r=read, w=write, x=execute, p=private, s=shared

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.