繁体   English   中英

以下fork程序的输出是什么?

[英]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;
}

我得到的输出如下:

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)

我已经运行了100次,并且总是得到ABD ... terminate ... CD “ D”总是在“ B”之前。 这是随机的还是我看不到的原因?

谢谢。

确切的输出完全取决于操作系统如何调度每个进程。 父母与第一个孩子之间没有同步,因此“ B”和“ D”可以按任何顺序打印。

例如,在我的机器上,我得到“ ADB(最终)CD”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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