[英]Linux c fork - process dont stop
我正在嘗試使用管道創建簡單的程序。 不幸的是,程序沒有像某些描述符未關閉那樣正確結束。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
int main(){
int fd[2];
pipe(fd);
if(fork()==0){
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("ls", "ls", NULL);
}
else{
if(fork() == 0){
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("tr", "tr", "a-z", "A-Z", NULL);
}
}
return 0;
}
只要所有功能都成功(不過,您絕對應該在生產版本中進行錯誤檢查),程序就可以正常工作。
但是,如果要等待兩個孩子:
wait(0); wait(0); //also skimping on the error checking
//stuck
return 0;
它會被卡住,因為tr
會嘗試讀取其整個stdin
(管道),並且只要父級仍然持有對寫入端的引用,管道就無法結束。
用
close(fd[1]);
wait(0); wait(0); //also skimping on the error checking
//stuck
return 0;
它應該再次運行平穩。
該程序給人的印象是“沒有結束”,因為這兩個操作都是在分叉的過程中完成的,並且主過程在2個子代之前死掉,因此在打印結果之前將手交還給shell 。
在return 0
之前添加此行
wait(NULL);
讓主要過程等待所有孩子死后再解決。
請注意,您也無法再次分叉主進程(執行tr
),您將獲得相同的結果。
else{
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("tr", "tr", "a-z", "A-Z", NULL);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.