I'm just starting to
fork() and I'm having some difficulties understanding the parallel execution. I've found this example code and I want to know if the first time it will go
false (I know if
pid1==0 it means it's a child, etc). I also want to know how many copies (children will be created) and some details on the general execution.
I have tried to run it and added the
return 0; (my original source didn't have it) just to see if exits... but as you can see it "waits"
int pid1, pid2, pid3, pid4;
printf("\t\t IF(TRUE) pid1=%d and pid2=%d and pid3=%d\n",
pid1, pid2, pid3);
printf("\nIF(False) FATHER is talking with pid1=%d and pid4=%d\n",
Best How To :
This program creates five descendant processes, and makes six calls to
printf, of which four will be the
IF(TRUE) message and two will be
IF(FALSE). Here is an ASCII-art diagram of the control flow; every time it branches, both sides are executed, with the parent going straight down and the child to the right. The numbers are the
fork calls initializing the
pid2, ... variables, the letters T and F are the
IF(FALSE) messages, and the
_ is the
return 0 at the end of the function. This program does not wait for anything; all control flow paths reach the
return 0 eventually.
3 3 | |
|\ |\ | |
T T T T F F
| | | | | |
_ _ _ _ _ _
The output messages may appear in any order. And it's possible that the topmost parent process will exit (returning control to the shell) before all of the descendant processes have written their messages, so (as is visible in your screeenshot) the shell prompt may get jumbled up with the messages, too.
Note that, going by the text of the messages, you have your
if conditional backward:
pid1 != 0 is true in the parent, not the child.