作者:也许_枉然 | 来源:互联网 | 2023-05-18 17:01
Ihavethemainprocessforkingtwotimesandthuscreatingtwochildren.Thetwochildrenarepiped
I have the main process forking two times and thus creating two children. The two children are piped with each other like this:
我有两次主要的过程,因此创造了两个孩子。这两个孩子彼此用管道输送:
ls | more
Now the problem is that the second child never dies. Why is that? When does the last child in a pipe die really?
现在问题是第二个孩子永远不会死。这是为什么?管道中的最后一个孩子什么时候真的死了?
Removing one wait() call shows the expected result of ls | more
but gives some further weird behaviours(stuck terminal etc).
删除一个wait()调用会显示ls |的预期结果更多,但给出了一些更奇怪的行为(卡住终端等)。
Here is my code:
这是我的代码:
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;
}
2 个解决方案