title: Bad file descriptor error when implementing piping in C
body: <p>I am trying to implement a sample shell like program which executes the command ls | wc </p>
  
  <p>Using pipes to implement the command. When I execute the command I get the following error.</p>
  
  <p>wc: standard input: Bad file descriptor
  0 0 0
  wc: -: Bad file descriptor</p>
  
  <p>Please take a look at the code and provide inputs
  Note: 1) parse is a library which takes in the input typed and returns each command as a linked list with args and necesary data. Parse is working fine
  2) I am executing each command in a different subprocess hence the fork </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include "parse.h"
  
  int pip[3][2];
  int main(int argc, char *argv[], char *envp[])
  {
      Pipe p; 
      Cmd c;
      pipe(pip[0]);
      pipe(pip[1]);   
      pid_t pid;
      pid=fork();
      char *host = "armadillo";
      printf("%s%% ", host);
      p = parse();
      c=p-&gt;head;  
      printf("1 \n");
      pid=fork();
  
      if(pid==0)
      {
          close(pip[0][0]);
          close(STDOUT_FILENO);
          dup2(pip[0][1],STDOUT_FILENO);
          execvp(c-&gt;args[0],c-&gt;args);
      }
      else
      {
          waitpid(pid,NULL,0);
      }
      printf("2 \n");
  
      close(pip[0][1]);
      close(pip[0][0]);
  
      c=c-&gt;next;
      printf("%s \n",c-&gt;args[0]);
      pid=fork();
      if(pid==0)
      {
          close(STDIN_FILENO);
          dup2(pip[0][0],STDIN_FILENO);
          close(pip[0][1]);
          execvp(c-&gt;args[0],c-&gt;args);
      }
      else
      {   
          waitpid(pid,NULL,0);
          close(pip[0][1]);
          close(pip[0][0]);
      }
  
  }
  </code></pre>