如何将"sort"程序的输出从子程序重定向到父程序

how to redirect output of "sort" program from child to parent

本文关键字:程序 子程序 重定向 sort 输出      更新时间:2023-10-16

我想做的是使用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);