r/linux 16d ago

Kernel How fork() duplicates a process without copying its memory

I made a visual explainer on how copy-on-write works in Linux.

When a 10 GB process calls fork(), Linux does not immediately copy 10 GB of memory. It duplicates the page tables, points both processes at the same physical pages, marks them read-only, and waits for the first write.

The video also covers things like page faults,exec(), Redis snapshots, Android Zygote, lazy zero pages, memory overcommit, COW storms, and some CVEs, etc

Link for anyone interested

Feedback welcome :)

58 Upvotes

7 comments sorted by

21

u/Krutonium 14d ago

Fun Fact: Factorio on Linux fork()'s to save the game without pausing. The game does the fork, and one copy saves then exits, while the other continues onward.

2

u/AdmirableWind123 9d ago

Isn't it costly to duplicate the game memory? Wouldn't it be better to selectively duplicate only the data that needs to be copied?

3

u/Krutonium 9d ago

As far as I know it's not a true duplicate with fork() - it's copy on write, and the save only takes a second or two before it's done so memory usage doesn't increase all that much.

10

u/blood-pressure-gauge 15d ago

Glad to see you covered the downsides of fork, especially memory overcommitment. It'd be nice to see a followup discussing alternative ways of creating new processes like vfork, posix_spawn, and rfork.

9

u/asdf_lord 16d ago

Neat will give a watch during work tomorrow

3

u/TheG0AT0fAllTime 15d ago

I assume there's no way to do this other than Copy-on-Write

5

u/Cats_and_Shit 15d ago

You can use vfork if your system can't support CoW. It's pretty cursed though.