如何将“排序”程序的输出从子项重定向到父项

时间:2013-03-10 04:39:30

标签: c++ c

我想要做的是使用pipe1从父级向子级发送随机数。然后子进程exec sort程序将这些数字排序并使用pipe2发送回父进程。现在我可以从stdout得到正确的排序结果,如果我注释掉“if(pipe2In> = 0){dup2(pipe2In,1); close(pipe2In);}”但是我无法从父项中的pipe2读取它们如下。实际上,读取呼叫无法返回。我错过了什么吗?感谢任何帮助。

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, "%d\n", rn);
    write(pipe1In, bufWrite, len+1);
}
char bufRead[1024];
int n;
while ( n = read(pipe2Out, bufRead, sizeof(bufRead)) != 0)
{
    printf("read count %d\n", n);
}
}

1 个答案:

答案 0 :(得分:2)

sort在输入流上收到EOF之前不会提供任何输出。要触发它,在您的父进程中,您应该在读取循环之前close(pipe1In);