Memory mapping and shared memory
Quick answer
mmap maps a region into a process’s virtual address space so bytes can be accessed through memory operations. Mappings can be backed by files or anonymous memory and can be shared or private. They are not automatically faster or safer than explicit reads.
A private mapping can reflect local writes without updating the underlying file. A shared mapping permits sharing changes but does not replace synchronization or durability handling. Use a tiny temporary file to compare mapping behavior and inspect the file afterwards.
Prepare the practice environment
Run python3 lab-fixtures/syscalls/setup.py from the extracted root as an ordinary user. Enter the printed fresh private path and check pwd. Use fresh fixtures, Bash with set -e -o pipefail, LC_ALL=C and umask 077. Run each snippet in a separate Bash process, not your interactive shell. Examples use Python 3 standard-library wrappers on Linux, private files, bounded child processes and local socketpairs. No root or external network is needed. Optional strace inspection requires an authorized environment. Review the lab guide.
Prerequisites
Review: Sockets and readiness.
How it works
MAP_SHARED permits updates to be visible through other shared mappings of the same region; file-backed changes can propagate to the file. MAP_PRIVATE creates a copy-on-write view whose updates do not modify the backing file. PROT_READ and PROT_WRITE select mapping protections. File offsets must meet alignment requirements; do not access past the mapped file, especially if another process truncates it (possible SIGBUS). munmap releases the mapping, independently of closing the original descriptor. Anonymous shared mappings inherited through fork can communicate bytes, but synchronization is still required. flush/msync and fsync address different parts of persistence; visibility is not crash durability. Python mmap offers access modes and flags; these small samples use private temporary files and a single-threaded fork, not real database storage. See mmap(2), msync(2), shm_overview(7).
Try the examples
python3 - <<'PYCODE'import mmapwith open('message.txt', 'rb') as f: with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as region: assert region[:5] == b'hello' print('mapped bytes:', region[:5].decode())PYCODEA memory slice reads bytes from a read-only mapping of the fixture; no explicit file read is used inside the mapping.
Expected stdout:
mapped bytes: hellopython3 - <<'PYCODE'import mmap, tempfilewith tempfile.TemporaryFile(dir='.') as f: f.write(b'abc'); f.flush() with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as private: private[0:1] = b'x' f.seek(0); assert f.read() == b'abc' print('private: backing abc') with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE) as shared: shared[0:1] = b'y'; shared.flush() f.seek(0); assert f.read() == b'ybc' print('shared: backing ybc')PYCODEACCESS_COPY modifies only the mapping; ACCESS_WRITE modifies the file-backed region. The check verifies visibility, not power-loss durability.
Expected stdout:
private: backing abcshared: backing ybcpython3 - <<'PYCODE'import os, mmapwith mmap.mmap(-1, 16, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE) as region: pid = os.fork() if pid == 0: region[:4] = b'done' os._exit(0) _, status = os.waitpid(pid, 0) assert os.waitstatus_to_exitcode(status) == 0 assert region[:4] == b'done' print('child update visible after wait')PYCODEThe parent waits for the child to finish before reading; concurrent writers would need an appropriate synchronization primitive.
Expected stdout:
child update visible after waitCommon mistakes
Do not confuse shared visibility with synchronization or durable storage. Do not map empty files or resize backing files while other processes access them.
Practice
Change the private and shared replacement bytes and verify the backing contents. Explain why the child example waits before reading and how simultaneous writers would differ.
Related references
Study: pmap. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory mapping and shared memory — Knowledge Check
Apply Linux systems programming interfaces to concrete local examples.
Which mapping propagates file-backed changes?
What does MAP_PRIVATE provide?
What happens to a mapping when its original fd closes?
Why wait before reading the shared anonymous mapping?