Contents
Does fork use copy-on-write?
In Linux, fork() is implemented through the use of copy-on-write pages. This technique delays the copying of each page in the address space until it is actually written to. In the case that the pages are never written—for example, if exec() is called immediately after fork()—they never need to be copied.
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. Here we show how they can share memory, so that when one updates it, the other can see the change. In this case we find that the child reads all the values written by the parent.
Does Linux use copy-on-write?
Copy-on-write pages are also used in the Linux kernel’s kernel same-page merging feature. Loading the libraries for an application is also a use of copy-on-write technique.
What happens to the memory of a forked process?
Yes, your forked process receives copies of all privately mapped memory (default memory mappings via malloc, calloc, stack frames, global variables) Your child receives shared copies of all open file descriptors. Means those file descriptors will remain valid and open until both parent and child close them.
How does fork copy a page in Linux?
Linux does Copy-on-Write. As fork creates a new process, the allocated pages are marked as readonly and shared between the parent and child. When either of them tries to modify a page, a page fault is generated resulting in copying the page and adjusting the page table appropriately.
Can a fork call create a duplicate stack?
Yes, theorically, the fork system call will duplicate, among other, the stack of the parent. In pratical, otherwise, there is a common method, named copy-on-write, used in that case. It consists on copy a given parent’s memory page only when the child’s process is trying to modify this memory space.
This not only affects the heap, but also shared libraries, stack, BSS areas. Which, incidentally, means that fork is a extremely lightweight operation, until the resulting 2 processes (parent and child) actually start writing to memory ranges.