pid_t pid;
printf("Begin");
if (fork() == 0) {
printf("First if fork==0");
if (fork() != 0)
printf("First if fork!=0");
}
if (fork() != 0) {
printf("second if fork!=0");
if (fork() == 0)
printf("second if fork==0");
}
printf("End if\n");
I try to understand how fork
works.
Can you draw a process graph to be understandable for me and for others?
Your example has four fork
s. Typically this is done differently
pid_t child_pid = fork();
// both parent and child process return from `fork()` and continue here
if (child_pid == -1) {
// still parent process, error handling
// no child process was created
} else if (child_pid == 0) {
// this is the child process
} else {
// this is the parent process, child_pid > 1
}
Now you can clearly see, which code is run in the parent, and which one is run in the child process.
Back to your example, you have a main process doing the fork
s (ignoring error handling)
if (fork() == 0) {
printf("First child process\n");
if (fork() != 0)
printf("First child process (parent part)\n");
/*
else
printf("Grandchild\n");
// fall through for both first child and grandchild
*/
}
// Main process, and first child, and grandchild
if (fork() != 0) {
// also first child and grandchild ("parent" part)
printf("Main process (parent part)\n");
if (fork() == 0)
// also third grandchild, and second great-grandchild
printf("Third child process\n");
}
/*
else
// also second grandchild, and first great-grandchild
printf("Main process, second child\n");
*/
This means, you have a main process, having three children. The first of the child processes does a fork too, creating a grandchild.
But, both the first child and the first grandchild continue with the same code to the second outer if, and so create additional children, grandchildren, and great-grandchildren.
So, in the end the main process has three children. From the first child, three grandchildren descend, of which the first grandchild has two great-grandchildren of its own.
Unless I forgot one or two or so, of course :-)