Skip to content

35. Memory-Mapped Files

Instead of read()/write() syscalls, mmap() maps a file directly into your process's virtual address space — you access it like an array.

How it works: mmap() maps the file (no data loaded yet — lazy) → you touch an address → page fault → OS loads that page from the file into RAM → you read/write like normal memory → changes sync back on flush/unmap.

Normal I/O vs mmap: normal I/O copies data disk→kernel buffer→user buffer (two copies, two context switches per read). mmap loads a page directly into your address space once — one copy, no repeated syscalls.

Mapping types: MAP_PRIVATE — changes are copy-on-write, never written back (used for loading executables/libraries). MAP_SHARED — changes are written back and visible to other processes mapping the same file (used for IPC, databases).

Real uses: loading executables (pages loaded on demand → fast startup), shared libraries (.so/.dll — one physical copy shared by many processes), databases (PostgreSQL/SQLite rely on the OS page cache), and as the fastest IPC method available (two processes MAP_SHARED the same file).