Appearance
33. Copy-On-Write (COW)
Problem: naively copying all of a process's memory on fork() is wasteful if the child immediately calls exec().
Core idea: don't copy anything at fork time — parent and child share the same physical pages, both marked read-only. A page is copied only when either side tries to write to it.
Step by step: fork() copies page table entries (not the pages themselves), both marked read-only → a write triggers a protection fault → the OS makes a private copy for the writer → both copies marked writable again → writes are now isolated.
Why it's efficient: if the child calls exec() immediately (replacing its whole address space), zero pages were ever copied — fork() cost was near zero. If the child only touches 2 of 500MB, only those 2 pages get copied.
COW beyond fork(): filesystem snapshots (APFS, Btrfs, ZFS — instant, cheap), containers (Docker layers share a COW filesystem, each container only stores its own changes), Redis background save (child sees a memory snapshot via COW while the parent keeps serving), shared libraries via mmap().
Analogy: like sharing a Google Doc — no copy is made until someone starts actually editing.