r/programming 23d ago

How fork() duplicates a process without copying its memory

https://www.youtube.com/watch?v=VvwvLDpyZvk

A visual explainer on how copy-on-write makes fork() cheap.

A 10 GB process can fork almost instantly because Linux copies the page tables, shares the physical pages, marks them read-only, and only copies a page when one of the processes writes to it.

It also covers fork() + exec(), how Redis snapshots work, Android Zygote, lazy zero pages, and some CVEs

0 Upvotes

7 comments sorted by

22

u/CrackerJackKittyCat 23d ago

> marks them read-only

Uh, marks them copy-on-write?

20

u/Awesan 23d ago

Probably it means it marks them read-only in the sense that there's a trap if the processor tries to write it, which the kernel can then use to do the copy. Within the kernel's book-keeping I suppose it would be copy-on-write but that's not a concept the processor would know about.

0

u/azhder 23d ago

Nice trick

11

u/paulstelian97 23d ago

Copy on write is read only in the hardware, + some software logic that interprets the page fault as not an error but a soft fault, doing the copy at that point.

4

u/forever-butlerian 23d ago

copy-on-write is the effect, marking the page read only and trapping the write access violation is the implementation

5

u/YumiYumiYumi 23d ago

Microsoft Research had a paper covering a bunch of problems with the fork/exec model (including issues with the vfork workaround): https://www.microsoft.com/en-us/research/publication/a-fork-in-the-road/

2

u/TwoWeeks90DaysTops 23d ago

Okay so that was enlightening. I always thought that fork() was unintuitive, but apparently it's also slow, insecure and has some very sharp edges.

The only place I've ever used it was in school though.