-1

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");
Peter
  • 437
  • 1
  • 4
  • 20

3 Answers3

3

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.

koder
  • 2,038
  • 7
  • 10
  • So, is the output BAB? Parent prints B Child prints A follow by B? – Peter Jan 31 '21 at 13:48
  • @Peter, or ABB as after `fork` it is undefined which process runs next. So the child may run before the parent gets a chance to print its B. – koder Jan 31 '21 at 14:36
1

fork On success, returns the PID of the child process to the parent, and 0 is returned in the child.

On failure, -1 is returned in the parent, no child process is created.

The errno is set appropriately.

What your piece of code doing is just checking it is the child process

// The second program
if (fork() == 0)
{
    // Would this ever be reached?
}
IrAM
  • 1,720
  • 5
  • 18
0

You seem to be ok with ...

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

..., and yet to question ...

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

. It's unclear, however, why you think there is a difference with any significance for the evaluation of the conditional.

In both cases, fork() is called. In the first code, its return value is recorded in a variable, and then the recorded value is tested for equality with zero (in both parent and child, supposing that fork() succeeds). In the second code, fork()'s return value is tested for equality with zero directly, without capturing it in a variable. There is no reason to think that this would produce a different comparison than in the first code.

And yes, if fork() succeeds then it will return zero in the child process and non-zero (the child's process ID) in the parent process, so whichever form is used, the == 0 branch will be taken in the child, but not in the parent.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157