我的主要過程是分叉兩次,從而創建兩個孩子。這兩個孩子是這樣彼此管道:最後一個分叉的孩子不會死亡
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