In this lesson, you will learn how Linux avoids wasting system memory when a process creates a child through the fork() system call.
The Problem with Duplication
When you spawn a new process using fork(), the kernel creates a complete copy of the parent process's memory space. If a large program (like a web server or a database) were to literally copy gigabytes of data every time it spawned a task, the system would immediately run out of RAM and grind to a halt.
The Solution: Copy-on-Write (CoW)
Copy-on-Write is a brilliant optimization strategy where the kernel avoids copying memory until it is absolutely necessary.
When fork() is called, the kernel does not copy the physical memory pages. Instead, it marks the memory pages of both the parent and the child as read-only. The two processes essentially "share" the same physical RAM.
As long as both processes only read from that memory, they can continue sharing those pages indefinitely without any extra memory usage.
What Triggers the Copy?
If either the parent or the child attempts to write to one of those shared pages, the hardware triggers a "page fault." The kernel intercepts this:
- It sees that the process is trying to modify a read-only page.
- It allocates a brand-new physical page of memory.
- It copies the contents of the original page into this new, private page.
- It updates the process's page table to point to the new, writable copy.
This ensures that the modification is invisible to the other process, maintaining strict isolation while delaying the heavy lifting of copying data until the very last second.
Visualizing the Efficiency
Imagine a parent process has 1GB of data.
- Without CoW: Spawning a child consumes another 1GB of RAM. Total: 2GB.
- With CoW: Spawning a child consumes almost 0MB of extra RAM. If the child only modifies 10MB of data, the total system memory usage is only 1.01GB.
Key Takeaway: Copy-on-Write creates memory efficiency by sharing physical RAM between processes and only duplicating pages when a process actually attempts to write to them.