谁帮我看看这样重定向标准输入输出,通过管道有什么错呀?
目的是在实现类似SHELL中的 | 管道符号的功能,比如将|符号前面程序的输出作为后面程序的输入
我使用管道描述符和dup2函数重定向前面程序的标准输出到管道,后面程序的标准输入从管道读,有哪里不对亚?
现在如果执行more test.c | grep "s"则什么都没有输出(test.c里有字符s的),如果执行cal | ls则只输出ls的内容
为什么阿?
if (pipe(fd) < 0)
err_sys("pipe error");
if ( (pid = fork()) < 0)
err_sys("fork error");
else if (pid > 0)
{
close(fd[0]); // 前面的程序关闭读端
if(dup2(fd[1],STDOUT_FILENO) == -1) // 前面的程序重定向标准输出到管道
err_sys("dup2 error");
//close(fd[1]);
execvp(command[0][0], command[0]);
err_ret("couldn't execute: %s", buf);
exit(127);
}
close(fd[1]); // 后面的程序关闭写端
if(dup2(fd[0],STDIN_FILENO) == -1) // 后面的程序重定向标准输入从管道
err_sys("dup2 error");
//close(fd[0]);
execvp(command[1][0], command[1]);
err_ret("couldn't execute: %s", buf);
exit(127);
问题点数:50、回复次数:8Top
1 楼fierygnu(va_list)回复于 2006-03-10 14:29:40 得分 0
这样只能父子进程间通信。你要实现的是什么?是shell?Top
2 楼lanying(蓝鹰)(问个不休)回复于 2006-03-10 19:37:53 得分 0
关注一下Top
3 楼victor03(dullboy)回复于 2006-03-10 19:58:13 得分 0
你写的dup2错了:
int dup2(int file_descriptor_one,int file_descriptor_two);
dup2创建的新文件描述符或者与file_descriptor_two相同,或者是第一个大于file_descriptor_two的可用值。所以在调用dup2时必须先调用:
close(STDOUT_FILENO);
才能将其重定向到STDOUT_FILENO.(下面的也一样)
Top
4 楼phus(phus)回复于 2006-03-10 21:11:52 得分 50
楼上的是以己昏昏,使人昭昭.Top
5 楼fierygnu(va_list)回复于 2006-03-10 22:05:13 得分 0
:)Top
6 楼aqhlwwx()回复于 2006-03-10 22:53:00 得分 0
是实现Shell呀。。。
父进程输出到子进程吧...
类似于more test.c | grep "s"这种的Top
7 楼aqhlwwx()回复于 2006-03-11 00:40:46 得分 0
for (i=0;i<pipeLevel;i++)
{
if (pipe(fd[i]) == -1)
err_sys("pipe error");
}
for (j=0;j<pipeLevel;j++)
{
if (j != 0)
pipe_in = fd[j-1][0];
else
pipe_in = -1;
if (j != pipeLevel-1)
pipe_out = fd[j][1];
else
pipe_out = -1;
if ( (pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
{
if (bg <= 0)
{
if (pipe_in == -1)
close(pipe_in);
if (pipe_out == -1)
close(pipe_out);
if (pipe_out != -1)
{
dup2(pipe_out,1);
close(pipe_out);
}
if (pipe_in != -1)
{
dup2(pipe_in,0);
close(pipe_in);
}
execvp(command[j][0], command[j]);
err_ret("couldn't execute: %s", buf);
exit(127);
}
// 父进程等待子进程结束
if ( (pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
close(pipe_in);
close(pipe_out);
....
这样还是不行!
more test.c | grep "s"
还是什么都显示不出!Top
8 楼fierygnu(va_list)回复于 2006-03-11 19:50:34 得分 0
execvp执行的什么?Top




