我的主要过程是分叉两次,从而创建两个孩子。这两个孩子是这样彼此管道:最后一个分叉的孩子不会死亡
ls | more
现在的问题是,第二个孩子永远不会死。这是为什么?什么时候管道中的最后一个孩子真的死了?
删除一个wait()调用显示ls | more
的预期结果,但给出了一些更奇怪的行为(卡住终端等)。
这里是我的代码:
int main(){
printf("[%d] main\n", getpid());
int pip[2], i;
pipe(pip);
/* CHILDREN*/
for (i=0; i<2; i++){
if (fork()==0){
/* First child */
if (i==0){
printf("[%d] child1\n", getpid());
close(1); dup(pip[1]);
close(pip[0]);
execlp("ls", "ls", NULL);}
/* Second child */
if (i==1){
printf("[%d] child2\n", getpid());
close(0); dup(pip[0]);
close(pip[1]);
execlp("more", "more", NULL);}
}
}
wait(NULL); // wait for first child
wait(NULL); // wait for second child
return 0;
}
这个问题的标题听起来非常暴力。 – Marlon
@Marlon哈哈直到现在都没有看到它那样! – Pithikos