简体   繁体   中英

What is the output of the following fork program?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM