在這里,我嘗試在 c 中使用管道實作 linux shell 腳本,我嘗試通過將第一個子行程的輸出傳遞給第二個子行程來實作,然后執行“grep a”,然后它應該像這樣回傳 a 1 a 4,它應該結束程式。但是我遇到的是,第二個子行程的輸出是正確的,“grep a”的輸出確實出來了,但是子行程卡在那里并且不會自行終止,誰能向我解釋為什么會這樣?我的父行程一直在等待第二個子行程結束。但它只是因為某種原因永遠停留在那里。
/* pipe4.c */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
int main(int agrc, char* agrv[])
{
int pipefds[2];
pid_t pid;
pid_t pid2;
int status;
if(pipe(pipefds) == -1){
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if(pid == -1){
perror("fork");
exit(EXIT_FAILURE);
}
if(pid == 0){
//replace stdout with the write end of the pipe
dup2(pipefds[1],STDOUT_FILENO);
//close read to pipe, in child
close(pipefds[0]);
execlp("cat","cat","try.txt",NULL);
}else{
waitpid(pid, &status, 0);
printf("first child done\n");
pid2 = fork();
if(pid2 == 0){
printf("second child start\n");
dup2(pipefds[0],STDIN_FILENO);
close(pipefds[1]);
execlp("grep","grep","a",NULL);
}
else{
waitpid(pid2, &status, 0);
printf("second child end\n");
close(pipefds[0]);
close(pipefds[1]);
exit(EXIT_SUCCESS);
printf("end\n");
}
}
}
uj5u.com熱心網友回復:
grep正在等待所有行程關閉管道的寫入端。grep在關閉管道的寫入端之前,父級正在等待完成。那是一個僵局。父級需要在呼叫之前關閉管道端waitpid
請注意,樣板為dup2:
dup2(pipefds[1],STDOUT_FILENO);
close(pipefds[0]);
close(pipefds[1]);
因為您需要關閉管道的兩端。我相信這不會在您當前的設定中引起問題,但不值得考慮太多。只需關閉管道的兩端。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515326.html
標籤:Clinux壳管道
上一篇:通過Shell腳本連接XML
下一篇:程式不會從文本檔案中讀取數字
