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;
}
输出我得到的是以下几点:以下fork程序的输出是什么?
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'之前。这是随机还是有我没有看到的原因?
谢谢。
你总是得到ADBCD,或者有时程序有时在第二个字母后终止?你似乎发布了矛盾的信息。 –
ABD ...终止... CD –
看到这个答案尤其是第四部分:https://stackoverflow.com/a/6697102/13422 –