我遇到有关多进程重定向标准输出的问题。
假设我有进程A,我在A中使用fork(),然后得到进程A和B。然后我在B中使用fork(),最后得到进程A,B和C。B和C都通过以下方式实现其他程序exec()。
现在,我尝试通过两个管道将A和B的标准输出重定向到C的标准输入。
#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的标准输入重定向到BtoC[0] ,它是进程B的标准输出。并且进程A的标准输出不传递到进程C的标准输入中。
我的问题是,是否有任何解决方案可以让我同时将进程A和B的标准输出重定向到进程C的标准输入。
另一个问题是,如果我也想在屏幕上打印进程A的标准输出,该怎么办? 我知道命令行中的命令tee 。 我尝试在进程A中使用相应的函数tee(int fd_in, int fd_out, size_t len, unsigned int flags) ,但我无法打印进程A的任何stdout。
任何建议表示赞赏,谢谢。