mko mko - 3 months ago 15
C Question

Why does return value of fork() have 2 pid value in C?


Possible Duplicate:

How is it possible for fork() to return two values?




I'm new to C, and I'm confused about the return value structure of the
fork()
function.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
pid_t childPid;
childPid = fork();
printf("%d\n",childPid);
return EXIT_SUCCESS;
}


The output is:

28501
0


Since
pid_
t is an
int
type, how does the
childPid
have 2 values?

Answer

You're actually seeing the output of two copies of the executable. When you call fork(), the process clones itself, giving two processes. The parent gets the child process's PID as the return value, and the child gets 0 as a return value.

The trick is, the clones share STDIN, STDOUT, and STDERR. When the parent reaches the printf, it prints the value it had, as does the child, so you see both PIDs, with both processes sharing the same STDOUT -- there's no obvious way to tell them apart in your program.

Try rewriting it as:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
  pid_t childPid;
  childPid = fork();
  if(childPid != 0)
      printf("I'm the parent and my child PID is %d\n",childPid);
  else
      printf("\tI'm the child, so I received  %d\n",childPid);

  return EXIT_SUCCESS;
}

and you'll see this more clearly.

For extra credit, look at the wait() syscall, and use it to make the parent terminate after the child.

Comments