so I am attempting to solve a problem in my book regarding the fork system call in C.
Here is the following code:
#include <stdio.h>
#include <unistd.h>
int main() {
int i = 1;
if (fork ()) //parent process will return PID of child.
i++;
else if (fork()) //child process (becomes parent)
i--;
else //grandchild process returns 0
i++;
printf("%d\n", i);
}
After going through the code, I got 2 0 2 as the solution. I am confused though since I don't know which order is correct? Can the child processes get printed out before the parent does? If so, another viable solution could be 0 2 2 or 2 2 0. How do I know if all the conditional statements will be executed? I know in the first conditional, the if statement will be executed and will be the parent process (which will return the process ID of the child, and the value of i will increment to 2). How would I know if the else if and elsecode will be executed? Sorry, I am just confused and trying to wrap my head around this as this is a new topic for me.
Any help would be greatly appreciated. Thank you in advance.
if (fork ())block, you can add a comment "first fork returned non-zero, this is the parent". And continue through the whole program.