views:

175

answers:

2

Does anyone see a problem with this, its not working saying bad file descriptor not sure why?

pipe(pipefd[0]);
if ((opid = fork()) == 0) {
     dup2(pipefd[0][1],1);/*send to output*/
     close(pipefd[0][0]);
     close(pipefd[0][1]);
     execlp("ls","ls","-al",NULL);
}

 if((cpid = fork())==0){
   dup2(pipefd[0][1],0);/*read from input*/
   close(pipefd[0][0]);
   close(pipefd[1][1]);
   execlp("grep","grep",".bak",NULL);
}

  close(pipefd[0][0]);
  close(pipefd[0][1]);
A: 

The indexes in the second block look suspect.

Ignacio Vazquez-Abrams
+1  A: 

Based on your code, I'm guessing pipefd is defined as:

int pipefd[2][2];

Now, when you do:

pipe(pipefd[0])

This only populates pipefd[0][0] and pipefd[0][1].

So when you do:

# Bad descriptor
close(pipefd[1][1]);

you are referencing random junk (you never set pipefd[1][0] or pipefd[1][1]).

From the code shown, I can't see why you aren't just doing:

int pipefd[2];
pipe(pipefd);
R Samuel Klatchko