Unix-like operating systems famously use the  fork system call for creating a new process. The way this system call works in the user code can be quit

Disillusioning the Magic of the fork System Call

submited by
Style Pass
2024-11-27 12:00:05

Unix-like operating systems famously use the fork system call for creating a new process. The way this system call works in the user code can be quite bewildering when you first learn about it. It creates a child process which is a copy of the parent (with few internal differences), when the system call returns back into user space, you may either be inside the child process or the parent, and you need to check the return value of fork to determine that. A typical example of using fork is shown below. The example uses the execve system call in the child to run the ls program while the parent prints a message on stderr and exits.

The confusing part here is: how can we simultaneously end up in both branches of an if condition? And how does a single system call return two values at the same time? Many books don’t go into the details to explain this, but it isn’t black magic. We can easily uncover the explanation by peeling back the layers of abstraction that hide the implementation details—and that’s exactly what we’ll do in this post

Support my work by becoming a paid subscriber. If you face trouble in paying on Substack, you can also support me via buymeacoffee or GitHub sponsorship. I’ll upgrade you to a paid subscription on Substack.

Leave a Comment