1
我想要做的是使用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);
}
}
工作,谢谢! – user2153006 2013-03-10 17:21:24