0
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.

K Split X
  • 3,405
  • 7
  • 24
  • 49
  • Do you always get ADBCD, or does the program sometimes terminate after the second letter? You seem to have posted contradictory information. – Daniel H Aug 15 '17 at 18:09
  • ABD ... terminate ... CD – K Split X Aug 15 '17 at 18:09
  • 1
    See this answer especially the part under Fourth: https://stackoverflow.com/a/6697102/13422 – Zan Lynx Aug 15 '17 at 18:10
  • 1
    Ah but then I found: https://stackoverflow.com/questions/17391201/does-proc-sys-kernel-sched-child-runs-first-work – Zan Lynx Aug 15 '17 at 18:22
  • The posted code has some significant oversights. 1) the necessary header file statements missing. 2) the returned type from a call to `fork()` is `pid_t` not `int` 3) both calls to `fork()` are missing the check(s) for an error return. 4) the top level and second level parent processes fail to wait for the child process to exit. (such oversights result in zombie processes) 5) with so many processes, the call to `wait()` doesn't know jst who it is waiting for. Strongly suggest using `waitpid()` (cont) – user3629249 Aug 17 '17 at 13:57
  • (cont) 6) the final line: `return 0;` will never be executed due to the preceding line contains `exit(0);` – user3629249 Aug 17 '17 at 13:59

1 Answers1

1

The exact output depends entirely on how the OS schedules each process. There is no synchronization between the parent and the first child, so "B" and "D" may print in any order.

For example, on my machine I get "ADB (end) CD".

dbush
  • 205,898
  • 23
  • 218
  • 273