I am aware that the child process will return 0 while the parent process will return the PID value of the child process. However, if multiple fork() functions are called, what would the return value be for the child of the child process (or processes that are forked >= 2 times)? For example in:
int main()
{
Fork();
Fork();
printf("hello\n");
exit(0);
}
fork() is called twice, and hence the child process will also continue forking. Thus regarding this, will the forked out processes from the child process all return to 0? Any help will be appreciated.
If we rewrite this code a little, the output might be illuminating.
int main()
{
int a, b;
printf("pid=%d\n",getpid());
a=fork();
printf("pid=%d a-fork=%d\n",getpid(), a);
b=fork();
printf("pid=%d a-fork=%d b-fork=%d\n",getpid(), a, b);
}
When I ran it, output of this was:
pid=285
pid=285 a-fork=286
pid=286 a-fork=0
pid=285 a-fork=286 b-fork=287
pid=286 a-fork=0 b-fork=288
pid=287 a-fork=286 b-fork=0
pid=288 a-fork=0 b-fork=0
So, the parent process calls fork and creates process 286. Then the parent process calls fork again, and creates process 287.
Meanwhile, process 286 calls fork and creates process 288
Graphically:
a-fork b-fork
285 -> 286, 287
286 -> 288
Note that the order of these could vary a bit. There's nothing to prevent the first child from forking before the parent completes the second fork.