What is copy-on-write (COW) in operating systems?
Why Interviewers Ask This
This tests whether you can apply Operating Systems knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Copy-On-Write (COW) is an optimization strategy where creating a "copy" initially shares the original data; the actual copy is made only when one of the parties modifies the data. This defers expensive copying until necessary and often avoids it entirely. fork() optimization (most important use): when fork() creates a child process, naively copying all of the parent's memory would be wasteful — many forks are immediately followed by exec() (which replaces memory). COW fork: both parent and child initially share the same physical pages (read-only); pages are marked copy-on-write in the page tables; when either writes to a page → page fault → OS copies the page → the writing process gets its own private copy; the other process continues using the original. Huge savings if child exec()s immediately. How COW works: (1) Pages shared, marked read-only + COW in page tables; (2) Write to shared page → hardware protection fault; (3) OS allocates new physical frame; (4) Copies content of original page to new frame; (5) Updates the writing process's page table entry to point to new frame (read-write); (6) Resumes execution. Other COW uses: file system snapshots (ZFS, Btrfs — write new data to new block, original preserved for snapshot); VM live migration (copy memory pages on modification); Redis AOF rewrite (fork() + COW); Python copy module and data structures. Refcount: each physical page has a reference count. COW copies when count > 1 and write occurs. After copy, both counts are 1 (exclusive). When count = 1, writes happen in place without copying.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Operating Systems answers easy to follow.