Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

On Linux, if you fork() and the forked (child) process exits are all the virtual memory pages still marked as copy-on-write in the parent?

I think the pages will stay marked as COW as anything else would probably be prohibitively expensive to implement, probably requiring per-page ref counts and other expensive book-keeping. But I was wondering the other day, if I fork a process to execute some code in a "stable snapshot" of the current process. What happens when the child process exits? Do all the memory pages in the parent stay marked as copy-on-write? That means that forking in a process with a lot of virtual memory (e.g. 128GB+) only to execute some code for a few minutes would cause lingering performance degradation in the parent process, for hours or even days afterward (not to mention the fork call itself which would not be cheap.)

I'm just curious as to what the actual behavior is on Linux (and I have no idea how I could test it.)

like image 962
Eloff Avatar asked Mar 23 '13 15:03

Eloff


People also ask

What does the fork () return to the child process?

Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.

What is shared between parent and child process when fork is done?

Answer: Only the shared memory segments are shared between the parent process and the newly forked child process. Copies of the stack and the heap are made for the newly created process.

Do forked processes share heap?

What fork() does is the following: It creates a new process which is a copy of the calling process. That means that it copies the caller's memory (code, globals, heap and stack), registers, and open files.

What forked process share?

Recall that when a process forks, the new child process has an identical copy of the variables of the parent process. After fork the parent and child can update their own copies of the variables in their own way, since they dont actually share the variable.


1 Answers

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.

like image 148
jbr Avatar answered Sep 17 '22 16:09

jbr