int main() {
int p1, p2;
printf("A\n"); // we always print A first
p1 = fork();
if (p1 == 0) { // child
printf("B\n");
p2 = fork(); // fork
if (p2 == 0) {
sleep(2);
printf("C\n");
exit(0);
}
wait(0); // parent waits for child to finish
}
printf("D\n");
exit(0);
return 0;
}
The output I get is the following:
A // always first
B or D // whether we are in parent or child. Program may be terminated here
C // always since parent of p2 waits
D // since p2 parent exits if condition, prints D, then exits(0)
I've run this a 100 times and always I get ABD ... terminate ... CD
. The 'D' always comes before the 'B'. Is this just random or is there a reason I am not seeing?
Thank you.