Search code examples
cif-statementunixforkunistd.h

What does fork() == 0 returns?


I have 2 programs and I'm very confused on the return of fork() in child process

The first program would call fork() and assign it to p. When p == 0, it implies child process.

// The first program
p = fork();
if (p == 0)
{
    // child process
}
else
{
    // parent process or exception
}

But what if we just call fork() == 0? I would think fork() return non-zero from it's docs. Hence the condition is never executed.

// The second program
if (fork() == 0)
{
    // Would this ever be reached?
    printf("A\n");
}

printf("B\n");

Solution

  • fork creates a new process as an identical copy of the process that calls it. And it returs twice. Once in the original caller (the parent process) with the PID of the newly created child and once in the newly create child with 0.

    So if you do if (fork() == 0) { ... }, the code inside the if body will run in the newly created child.

    Don't do that however, as the parent does need to know the PID of the child because it has to wait for it.