title: ls | wc using C doesn't work
body: <p>I'have written a C program which uses multiple piping to simulate shell. The problem is I can run most of the commands like <code>ls | cat</code> etc, but I'm unable to use <code>ls | wc</code>. Is there any case when <code>wc</code> doesn't work?</p>
  
  <pre><code>int pipefd[4]; 
  int p1 = pipe(pipefd);          // Open pipe 1
  int p2 = pipe(pipefd + 2);      // Open pipe 2
  
  pid_t pid;
  
  for(i = 0; i &lt; n_commands; i++)
  {
      fflush(stdout);
      pid = fork();
  
      if(pid == 0)
      {
          int command_no = i;
          int prev_pipe = ((command_no - 1) % 2) * 2;
          int current_pipe = (command_no % 2) * 2;
  
          // If current command is the first command, close the
          // read end, else read from the last command's pipe
          if(command_no == 0)
          {
              close(pipefd[0]);
          }
          else
          {
              dup2(pipefd[prev_pipe], 0);
              close(pipefd[current_pipe]);
          }
  
          // If current command is the last command, close the
          // write end, else write to the pipe
          if(command_no == n_commands - 1)
          {
              close(pipefd[current_pipe + 1]);
          }
          else
          {
              dup2(pipefd[current_pipe + 1], 1);
          }
  
          int p = execvp(tokens[cmd_pos[command_no]], tokens + cmd_pos[command_no]);
  
          close(pipefd[current_pipe]);
          close(pipefd[prev_pipe]);
          close(pipefd[prev_pipe + 1]);
          close(pipefd[current_pipe + 1]);
  
          _exit(0);
      }
  }
  </code></pre>
  
  <p>It seems that the programs from <code>/usr/bin</code> are not being executed if they are not the first command in the pipeline.</p>