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