gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:55:37 24 4
gpt4 key购买 nike

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 ...终止...CD。 “D”始终位于“B”之前。这只是随机的还是有我没有看到的原因?

谢谢。

最佳答案

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

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

关于c - 以下 fork 程序的输出是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com