Middle
What happens to the process memory when it is forked in Linux?
sobes.tech AI
Answer from AI
When fork() is called in Linux, a new process (child) is created, which is almost an exact copy of the parent process. The memory handling is as follows:
- Copying (not yet): Initially, instead of copying the entire address space of the parent, a "copy-on-write" (CoW) mechanism is used.
- CoW: Memory pages of the parent process are marked as read-only for both the parent and the child. Both processes share the same physical pages.
- Modification: Only when one of the processes (parent or child) attempts to write to a shared page does the Linux kernel allocate a new physical page, copy the contents of the original page to it, and redirect the virtual address of that process to the new physical page. The parent's page remains unchanged.
- Shared memory: Shared memory segments (e.g., System V Shared Memory or POSIX Shared Memory) are not duplicated. Both processes access the same physical shared memory segment.
- File descriptors: The file descriptor table is copied. This means the child has access to the same open files as the parent, with the same file pointer positions. However, closing a descriptor in one process does not affect the other.
- Stack: The current thread's stack in the parent process is copied for the child, allowing it to continue execution from the same point.
- Heap: The heap of the parent process is also subject to the CoW mechanism.
Thus, fork() is efficient because full memory copying occurs only when data is modified, saving time and system resources.