1

我想要做的是使用 pipe1 从父级向子级发送随机数。然后子进程执行sort程序对这些数字进行排序并使用 pipe2 发送回父进程。现在,如果我注释掉“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);
}
}
4

1 回答 1

2

sort直到它EOF在其输入流上接收到一个才给出任何输出。要触发它,在您的父进程中,您应该close(pipe1In);在读取循环之前。

于 2013-03-10T05:10:38.930 回答