I am trying to figure out how many processes are created with the following C code:
int main () { fork(); if (fork()) { fork(); } fork(); return 0; } There are a couple of things I am confused about:
Each time fork() is called, does the child start from the start of the code, or does it start where the current fork() created it from? For instance, if line 3's first fork is called, will I start the child at line 4, or line 1? I believe this is a stupid question, b/c it would create an infinite loop if each child started from the beginning, but I want to be safe about this assumption.
Next, when fork is called, does the current process split into two NEW processes, one being the parent, and the other the child, or is the current process automatically the parent, so really, just one extra process is created.
Lastly, with the if statement, I am pretty certain fork returns the value of the parent id when it is actually the parent, and always 0 when it is the child. So, am I correct to assume that the if statement will be false for every child spawned?
With all my assumptions above, this is the process tree I came up with, and would greatly appreciate if someone sees a fault that is throwing it off. The number of the children in the tree represent the line of code that the fork is currently happening:
main | | | | 3 4 5 7 // the main/initial process calls fork 4 times | | | | | 4 5 7 7 7 // the first fork will see 3 additional forks since it was called | | // at line 3 and I assume resumes at line 4. 7 7 // The second and third original children would each only callthe // very last fork(). The last fork has no other forks following. Therefore, there are 10 total processes created (including main). Did I do it wrong?