In my OS course, the instructor mentioned the following: In UNIX if a parent process creates a new child ("fork") then the child is an exact duplicate of the parent. This means its memory space is a copy of the parent's.
Now if the child process immediately calls "exec", it replaces its own memory space with that of a new program. This means that time spent in copying the parent's memory space is wasted.
So, UNIX has a solution copy-on-write. That is when a child is created the pages of the parent are shared with the child, they are also marked "copy-on-write". So, as long as both are solely reading the page one memory space is shared between the two. But when either of them attempts to modify a page, a new copy is made for that page and page is modified.
So, given this explanation, I have a few questions. Most of them are concerned with the boundary where the software ends and the hardware starts.
When a new process is being created, there is a trap to the OS. And the OS does what it does to create a new process. Now, if the pages are marked "copy-on-write" then what happens to the pages of the parent process that were already in cache?
They are evicted, right?
What I particularly don't understand is if the child process tries to write to some page that is still being shared between the parent and child, how will the copy happen?
From the perspective of the CPU (hardware) that is executing the child process, it makes a write request. There are two cases here: either there was a cache miss, or a cache hit (the page was (at some time) during a read request loaded into the cache).
If it was a cache hit then wouldn't the hardware just write to that page in the cache disregarding the "copy-on-write" policy of the OS? How would the OS ensure that "copy-on-write" is respected here?
If it was a cache miss then the request goes to the page table and the page address is retrieved but the question remains the same.
Since UNIX is not designed for a specfic hardware, how would it ensure that "copy-on-write" is actually happening? Or is there some hardware support to perform something like this? I looked into cache locking but I don't think that can be used here.
Can someone please explain this?