title: pipe: Bad file descriptor
body: <p>I'm trying to implement a simpel c shell that will pipeline an arbitrary number of commands. Here is the relevant for loop: </p>
  
  <pre><code>int status;
  int i,j,inputFile,outputFile,pid;
  int pipeNum = info-&gt;pipeNum;
  
  struct commandType *command;
  
  int pipes[pipeNum * 2];
  for(i=0;i&lt;pipeNum;i++){
    pipe(pipes+2*i);
    printf("PIPE NUMBER %d CREATED\n", i+1);
  }
  for(j=0;j&lt;=pipeNum;j++){
    if( ( pid=fork() ) ==0 ){
      if(j!=0){ 
        if(dup2(pipes[(j-1)*2],STDIN_FILENO)&lt;0){
        perror("pipe");
        exit(2);
        }
      }
      if(j!=pipeNum){
        if(dup2(pipes[2*j+1],STDOUT_FILENO)&lt;0){
        perror("pipe");
        exit(2);
        }
      }
      if(j==0 &amp;&amp; info-&gt;boolInfile==1){
        if((inputFile = open(info-&gt;inFile,O_RDONLY))&lt;0){
      perror("file");
      exit(2);
        }
        if(dup2(inputFile,STDIN_FILENO)&lt;0){
        perror("dup2");
        exit(2);
        }
      }
      if(j==pipeNum &amp;&amp; info-&gt;boolOutfile){
        if((outputFile = open(info-&gt;outFile,O_WRONLY | O_CREAT | O_TRUNC, 666)&lt;0)){
      perror("file");
      exit(2);
        }
  
        if(dup2(outputFile,STDOUT_FILENO)&lt;0){
        perror("dup2");
        exit(2);
        }
      }
      for(i=0;i&lt;pipeNum*2;i++){
        close(pipes[i]);
        }
      command=&amp;info-&gt;CommArray[j];
      execvp(command-&gt;VarList[0],command-&gt;VarList);
      perror("Bad command");
    }
    for(i=0;i&lt;pipeNum*2;i++){
      close(pipes[i]);
    }
    for(i=0;i&lt;pipeNum+1;i++){
      wait(&amp;status);
    }
  }
  </code></pre>
  
  <p>But when I try to run the command </p>
  
  <pre><code>cat file.txt | wc
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>pipe: Bad file descriptor. 
  </code></pre>
  
  <p>Does anybody see the flaw in my code here? I can't figure it out to save my life. </p>
  
  <p>I have added some print line statements and I get the bad file descriptor for every single pipe. ugh. </p>