Part 3 — File Mappings Linux Memory Mappings — Private & Shared File Mappings with mmap()

 

Chapter 49 · Part 3 — File Mappings
TLPI · Linux Memory Mappings — Private & Shared File Mappings with mmap()
📁 2 Tutorial Files
💻 10+ Code Examples
🎯 17 Interview Q&A
📖 Sections 49.4.1–49.4.2

This part of the Chapter 49 series covers how mmap() works with actual files — both the private mappings the kernel uses to load programs, and the shared mappings that enable memory-mapped I/O and fast IPC. These are among the most important and widely used kernel features in embedded Linux and systems programming.

🔑 Topics Covered
MAP_PRIVATE MAP_SHARED Copy-on-Write (COW) Memory-mapped I/O msync() munmap() mprotect() IPC via file mapping ftruncate() ELF text segment /proc/PID/maps Page Cache SIGBUS TLB flush

Tutorial Files

File 1 — Private File Mappings (Section 49.4.1)
MAP_PRIVATE Copy-on-Write (COW) ELF text & data segment loading /proc/PID/maps mmap() syntax mprotect() Debugger breakpoints Verify COW with code 8 interview Q&A

Covers why the kernel uses MAP_PRIVATE to map the text and data segments of every ELF binary, how Copy-on-Write works, and how to use private file mappings for simplified file input. Includes a working program that proves COW does not modify the original file.

Read File 1 →

File 2 — Shared File Mappings, Memory-mapped I/O & IPC (Section 49.4.2)
MAP_SHARED Memory-mapped I/O msync() — MS_SYNC / MS_ASYNC t_mmap.c example IPC via shared file Writer/Reader programs Structured data over mmap mmap vs read/write comparison ftruncate() SIGBUS 9 interview Q&A

Covers how shared file mappings work, memory-mapped I/O as an alternative to read()/write(), msync() for durability, and using shared file mappings for fast persistent IPC. Includes the classic t_mmap.c program, a writer/reader IPC pair, and a struct-based mapping example.

Read File 2 →

Quick Reference: MAP_PRIVATE vs MAP_SHARED

Property MAP_PRIVATE MAP_SHARED
Writes reach file? ✗ No — COW copies ✓ Yes — written back
Visible to other processes? ✗ No ✓ Yes
Use case Loading ELF text/data, file input Memory-mapped I/O, IPC
fd open mode O_RDONLY or O_RDWR Must be O_RDWR for PROT_WRITE
Physical pages shared? Yes (until first write) Yes (always)
msync() needed? Not applicable For durability / cross-process visibility

Part of the Linux System Programming Series

EmbeddedPathashala — Free embedded systems & Linux tutorials for engineers and students.

Visit EmbeddedPathashala

Leave a Reply

Your email address will not be published. Required fields are marked *