如何重定向“排序”的输出。程序从孩子到父母 [英] how to redirect output of "sort" program from child to parent

查看:191
本文介绍了如何重定向“排序”的输出。程序从孩子到父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是使用pipe1将随机数从父项发送到子项。然后子进程exec sort 程序,以获取这些数字,并使用pipe2发送回父进程。现在我可以得到正确的排序结果从stdout如果我注释掉if(pipe2In> = 0){dup2(pipe2In,1);关闭(pipe2In);}但我不能读取他们从pipe2在父级如下。实际上,读调用不能返回。我缺少什么?赞成任何帮助。

What I want to do is to send random numbers from parent to child using pipe1. Then child process exec sort program to get these numbers sorted and send back to parent process using pipe2. Now I can get the right sorted result from stdout if I comment out "if( pipe2In >= 0){ dup2(pipe2In, 1); close(pipe2In);}" but I can't read them from pipe2 in parent as follows. Actually, the read call can not return. Am I missing something? Appreciate any help.

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);
}
}


推荐答案

code> sort 不会给出任何输出,直到它在其输入流上接收到 EOF 。要触发它,在你的父进程中,你应该在读循环之前关闭(pipe1In);

sort doesn't give any output until it receives an EOF on its input stream. To trigger that, in your parent process you should close(pipe1In);before your read loop.

这篇关于如何重定向“排序”的输出。程序从孩子到父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆