如何将"sort"程序的输出从子程序重定向到父程序
how to redirect output of "sort" program from child to parent
我想做的是使用pipe1从父节点发送随机数到子节点。然后子进程执行sort
程序将这些数字排序并使用管道2发送回父进程。现在我可以从stdout中得到正确的排序结果,如果我注释出"if(pipe2In>= 0){dup2(pipe2In, 1);close(pipe2In);}"但是我不能像下面这样从parent中的pipe2中读取它们。实际上,read调用不能返回。我错过什么了吗?谢谢你的帮助。
const int READ = 0, WRITE = 1;
{
pid_t pid;
int pipe1[2], pipe2[2];
if ( pipe(pipe1) )
{
cerr << "Error! Pipe 1 Failed. errno = "<< errno << endl;
exit(1);
}
int pipe1In = pipe1[WRITE];
int pipe1Out = pipe1[READ];
if ( pipe(pipe2) )
{
cerr << "Error! Pipe 2 Failed. errno = "<< errno << endl;
exit(1);
}
int pipe2In = pipe2[WRITE];
int pipe2Out = pipe2[READ];
pid = fork();
if( pid < 0 )
{
cerr << "Error! Fork Failed!n";
exit( 1 );
}
else if ( pid == 0 ) // child
{
close(pipe1In);
close(pipe2Out);
if( pipe1Out >= 0 )
{
dup2( pipe1Out, 0 );
close(pipe1Out);
}
if( pipe2In >= 0)
{
dup2(pipe2In, 1);
close(pipe2In);
}
execlp("sort", "sort", "-nr", (char *)NULL);
cerr << "Error - Exec Failed!n";
exit( -2 );
} // end of child
close(pipe1Out); // parent continues from here
close(pipe2In);
// generate random numbers
int rn, tem, i, len;
for (i = 0; i < nWks; i++)
{
rn = rand();
tem = rn;
len = 1;
while (tem /= 10) len++;
char *bufWrite = (char *) malloc(len+1);
sprintf(bufWrite, "%dn", rn);
write(pipe1In, bufWrite, len+1);
}
char bufRead[1024];
int n;
while ( n = read(pipe2Out, bufRead, sizeof(bufRead)) != 0)
{
printf("read count %dn", n);
}
}
sort
在其输入流上接收到EOF
之前不给出任何输出。要触发它,在父进程中,您应该在读取循环之前close(pipe1In);
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 当使用 stdlib.h 中的 system() 从程序内部运行程序时,如何模拟键入以馈送子程序的 scanf 调用?
- 编写一个计算n的子程序.使用此子程序时,制作一个计算(a+b)的程序
- 使用Fortran 77子程序作为独立程序,从C++调用
- 分支子程序中与启动程序进行管道通信的要求
- 如何将"sort"程序的输出从子程序重定向到父程序