What exactly does fork return?

compiler picture compiler · Apr 7, 2011 · Viewed 68.1k times · Source

On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of execution.

p = fork();

I'm confused at its manual page,is p equal to 0 or PID?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Apr 7, 2011

I'm not sure how the manual can be any clearer! fork() creates a new process, so you now have two identical processes. To distinguish between them, the return value of fork() differs. In the original process, you get the PID of the child process. In the child process, you get 0.

So a canonical use is as follows:

p = fork();
if (0 == p)
{
    // We're the child process
}
else if (p > 0)
{
    // We're the parent process
}
else
{
    // We're the parent process, but child couldn't be created
}