I have this bit of code:
printf("L1 ");
if(fork() != 0) {
printf("L2 ");
if(fork() != 0) {
printf("L3 ");
fork();
}
}
printf("End \n");
As an exercise I am trying to figure out some examples of valid/ invalid output that would result from running this code (without actually running it).
I am still a bit confused with how the fork() method works exactly within an if-statement. I know that once it is called it returns twice, indicating that it has created two processes.So that if I did something like,
printf("L1 ");
fork();
printf("L2 ");
I would get L1 L2 L2
But I am still shaky on how it works in in statements like in the first bit of code.
Here is what I think are a few valid/ invalid outputs:
Valid: L1 L1 L2
L1 L2 L3
L1 L2 L1
Invalid: (Anything hat doesn't start with L1)
L1 L2 L2
L1 L3 L2
Doe these make sense? Is there an simple way to explain sort of what is going on in the if-statements so that I can get a general idea as to how the fork() works in them? And are these output values correct/ incorrect?
In your code, the child of each fork proceeds directly to the
printf("End")
. Only the parent will printL1
,L2
,L3
, so they'll only be printed once each, in that order. Mixed in with that output would be theEnd
s of the children (and the final end of the parent).If the
fork()
calls all fail, there'll only be one process, so it will print:If every
fork()
call succeeds, then:L1
and end withEnd
.fork()
returns a non-zero value, it is the parent process.if
fails in the first child, so it printsL1 End
.if
passes in the parent, and the subsequent outputs will then includeL2
.if
fails in the second child, so it printsL1 L2 End
.if
passes in the parent, and the subsequent outputs will then includeL3
.fork()
creates two processes (or creates one and continues in the parent), both of which printL1 L2 L3 End
.So, the output will consist of:
but the sequence is not guaranteed.
After posting the analysis above, I checked it by running it, and the first sample run produced:
Note that if the output is non-buffered, then the output is different.
L1
will appear once;L2
will appear once;L3
will appear once; andEnd
will appear four times.One possible sequence is:
Another observed sequence (second of two runs) was: