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?
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:
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.