in reply to Re^2: Keeping variables throug a fork
in thread Keeping variables throug a fork
How could memory split from a fork?
On a modern Unix-like memory system, fork() creates a new process within the kernel. The process has its own ID and its own scheduling. That's why multiple processes can execute more-or-less simultaneously.
Each process also has its own memory space. However, a fork()ed process begins execution from the point of the fork() call. Thus it needs to have a copy of the parent process's memory space. (It needs a copy so that they can have separate memory spaces, otherwise every process would have the potential to write into any other process's memory space, which would be bad for system stability.)
Because copying megabytes and potentially gigabytes of memory from one page into another every time you call fork() would be very expensive, modern Unix-like kernels use a copy-on-write scheme. Instead of copying the memory pages in a fork()ed child, the kernel copies only the page tables for the process. Think of this as a list of memory pages the process used. It also sets a special flag on each page table entry so that when anything writes to one of the pages, the kernel does the copy then, and writes the modifications to the copied entry.
This is very efficient for several reasons.
Because your code modifies a variable in the child process, whatever page of memory (or pages) used to store those values immediately get copied and go unshared. The parent process keeps the current page with the current values and the child process gets a new page with the new values.
(I realize as I write this that I don't know exactly how the kernel handles the situation where the parent process modifies a page shared with one or many children, but I'm pretty sure there's a copy there too.)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Keeping variables throug a fork
by BrowserUk (Patriarch) on Jul 06, 2007 at 11:20 UTC |