经典 C. 在 execvp 函数中使用管道,stdin 和 stdout 重定向 [英] Classic C. Using pipes in execvp function, stdin and stdout redirection
本文介绍了经典 C. 在 execvp 函数中使用管道,stdin 和 stdout 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的 Linux C 程序中使用管道和 execvp 函数模拟 bash.例如
I want to simulate bash in my Linux C program using pipes and execvp function. e.g
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);
}
这段代码实际上可以运行,但没有做正确的事情.这段代码有什么问题?这不起作用,我不知道为什么.
This code actually runs, but doesn't do the right thing. What's wrong with this code? That's not working and I don't have a clue why.
推荐答案
您需要关闭父级中的管道 fds,否则子级将不会收到 EOF,因为管道仍处于打开状态以供在父级中写入.这将导致第二个 wait()
挂起.对我有用:
You need to close the pipe fds in the parent, or the child won't receive EOF, because the pipe's still open for writing in the parent. This would cause the second wait()
to hang. Works for me:
#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;
}
这篇关于经典 C. 在 execvp 函数中使用管道,stdin 和 stdout 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文