Issue
In the book "Operating System Concepts" I found such a context:
In UNIX , as we’ve seen, each process is identified by its process identifier, which is a unique integer. A new process is created by the fork() system call. The new process consists of a copy of the address space of the original process. This mechanism allows the parent process to communicate easily with its child process. Both processes (the parent and the child) continue execution at the instruction after the fork() , with one difference: the return code for the fork() is zero for the new (child) process, whereas the (nonzero) process identifier of the child is returned to the parent.
It confuses me. Sounds like that the same fork()
function returns two different values to both of the parent and the child process? How can that be possible (one function returns two different values to two processes), or did I misunderstand it?
Solution
When you enter fork
, there's only a single process. While inside fork
, this single process is cloned/copied. Now there are two processes running the same code in parallel. Both processes are still inside the fork
function. Eventually, each process will exit the fork
function: the parent process will exit the fork function (returning the PID of the child) and the child process will exit the fork function (returning 0).
Fork (ASCII art):
,-- (parent process) child PID returned to parent
parent -- fork() --
`-- (child process) 0 returned to child
Fork (clip art):
Answered By - knittl Answer Checked By - David Goodson (WPSolving Volunteer)