If you fork() and the forked (child) process exits are all the VM pages still marked COW in the parent? If you fork() and the forked (child) process exits are all the VM pages still marked COW in the parent? linux linux

If you fork() and the forked (child) process exits are all the VM pages still marked COW in the parent?


Apart from the copy-on-write bit there is also a reference count in the page table. So when a child forks, all non-private pages in the parentent are marked COW, and the reference count is incremented.

Then while the child process is running, and the parent writes a page, it will get a page fault, and the page is copied like you would expect, and reference count is decreased. When the child exits, it decreases all its page references with one, and the pages with reference count zero are thrown away.

Now when the parent writes a page that has the COW-bit set, and a reference count of one, the COW-bit is simply ignored.


The kernel marks all of the shared pages as write-protected, thus resulting in an exception if either tries to modify one. The duplicate is created, and is marked as writable (thus no more exceptions), while the original remains write-protected.

If the original is written to, another exception occurs, but the kernel will see that the page isn't shared by any other process, and so will mark that one as writeable too. When a process terminates, all of its pages are released, and so the kernel will effectively remove the COW status from every page in the parent when it's modified.