[英]Classic C. Using pipes in execvp function, stdin and stdout redirection
我想在我的 Linux C 程序中使用管道和 execvp 函數模擬 bash。 例如
ls -l | wc -l
有我的程序:
if(pipe(des_p) == -1) {perror("Failed to create pipe");}
if(fork() == 0) { //first fork
close(1); //closing stdout
dup(des_p[1]); //replacing stdout with pipe write
close(des_p[0]); //closing pipe read
close(des_p[1]); //closing pipe write
if(execvp(bash_args[0], bash_args)) // contains ls -l
/* error checking */
}
else {
if(fork() == 0) { //creating 2nd child
close(0); //closing stdin
dup(des_p[0]); //replacing stdin with pipe read
close(des_p[1]); //closing pipe write
close(des_p[0]); //closing pipe read
if(execvp(bash_args[another_place], bash_args)) //contains wc -l
/* error checking */
}
close(des_p[0]);
close(des_p[1]);
wait(0);
wait(0);
}
這段代碼實際上可以運行,但沒有做正確的事情。 這段代碼有什么問題? 這是行不通的,我不知道為什么。
您需要關閉父級中的管道 fds,否則子級將不會收到 EOF,因為管道仍處於打開狀態以在父級中寫入。 這將導致第二個wait()
掛起。 對我有用:
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int des_p[2];
if(pipe(des_p) == -1) {
perror("Pipe failed");
exit(1);
}
if(fork() == 0) //first fork
{
close(STDOUT_FILENO); //closing stdout
dup(des_p[1]); //replacing stdout with pipe write
close(des_p[0]); //closing pipe read
close(des_p[1]);
const char* prog1[] = { "ls", "-l", 0};
execvp(prog1[0], prog1);
perror("execvp of ls failed");
exit(1);
}
if(fork() == 0) //creating 2nd child
{
close(STDIN_FILENO); //closing stdin
dup(des_p[0]); //replacing stdin with pipe read
close(des_p[1]); //closing pipe write
close(des_p[0]);
const char* prog2[] = { "wc", "-l", 0};
execvp(prog2[0], prog2);
perror("execvp of wc failed");
exit(1);
}
close(des_p[0]);
close(des_p[1]);
wait(0);
wait(0);
return 0;
}
閱讀wait
函數的作用。 它將等待,直到存在一個子進程。 在開始第二個孩子之前,您正在等待第一個孩子退出。 第一個孩子可能不會退出,直到有一些進程從管道的另一端讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.