我遇到了关于多进程重定向stdout的问题.
假设我有进程A,我在A中使用fork(),然后我得到进程A和B.我在B中使用fork(),最后我得到进程A,B和C.B和C都在实现其他程序EXEC().
现在,我尝试用两个管道将A和B的stdout重定向到C的stdin.
#include
#include
#include
int main()
{
int AtoC [2];
pipe(AtoC);
int fd1,fd2;
fd1=fork();
if(fd1>0)
{
/***In process A, I do the following steps: ***/
close(AtoC[0]);
dup2(AtoC[1], STDOUT_FILENO);
/* program running in process A */
}
else
{
int BtoC [2];
pipe(BtoC);
fd2=fork();
if(fd2>0)
{
/***In process B, I do the following steps: ***/
close(AtoC[1]);
close(BtoC[0]);
dup2(BtoC[1], STDOUT_FILENO);
/*** execute another program in process B using execl(); ***/
}
else
{
/*** In process C, I do the following steps: ***/
close(AtoC[1]);
close(BtoC[1]);
dup2(AtoC[0],STDIN_FILENO);
dup2(BtoC[0],STDIN_FILENO);
/*** execute another different program in process C using execl(); ***/
}
}
}
现在,在这两个陈述之后:
dup2(AtoC[0],STDIN_FILENO);
dup2(BtoC[0],STDIN_FILENO);
进程C的stdin最终重定向到BtoC [0],这是进程B的stdout.进程A的stdout没有传递给进程C的stdin.
我的问题是,是否有任何解决方案可以让我同时将进程A和B的stdout重定向到进程C的stdin.
另一个问题是,如果我还想在屏幕上打印进程A的标准输出,我该怎么办?我在命令行中知道命令tee.我尝试在进程A中使用相应的函数tee(int fd_in,int fd_out,size_t len,unsigned int flags),但是我无法打印任何进程A的stdout.
任何建议表示赞赏,谢谢.