【发布时间】:2014-10-29 17:11:44
【问题描述】:
谁能解释一下为什么输出是这样的?我对这些进程的执行方式(按什么顺序?)以及waitpid()/wait() 感到非常困惑。
代码如下:
#include<stdio.h>
main()
{
int pid1, pid2, pid3;
pid1=fork();
if(pid1 == 0){
printf("PID of child 1 is :%d\n",getpid());
//sleep(2);
}
pid2=fork();
if(pid2 == 0){
printf("PID of child 2 is :%d\n",getpid());
//sleep(2);
}
pid3=fork();
if(pid3 == 0){
printf("PID of child 3 is :%d\n",getpid());
//sleep(2);
}
else{
printf("PID of parent is :%d\n",getpid());
waitpid(pid1,0,0);
waitpid(pid2,0,0);
waitpid(pid3,0,0);
}
}
实际输出:
PID of child 1 is :4963
PID of parent is :4962
PID of parent is :4963
PID of child 2 is :4966
PID of parent is :4966
PID of child 2 is :4964
PID of parent is :4964
PID of child 3 is :4967
PID of child 3 is :4965
PID of child 3 is :4969
PID of child 3 is :4968
预期输出:
父母的PID,因为pid1不是0,这里永远不会是0。
然后等到 pid1 即 child1 被终止并打印 child 1 的 PID
那么现在 child2 和 child3 还没有分叉,所以它们被跳过了
然后是父母的PID,child1的pid,child2的pid
然后是父母的PID,child1的pid,child2的pid和child3的pid。
请问我哪里出错了?
【问题讨论】: