title: Linux shell simulation: stuck on multiple pipes
body: <p>I know similar questions have already been asked but none of the replies helped me. I am trying to implement a miniature Linux shell and am stuck on multiple pipes. Commands with a single pipe (e.g. <code>ls | wc</code>) work, but if I add a second pipe, nothing is shown on the console. Here is my code.</p>
  
  <pre><code>void ExecuteCommand(NODE *cHead,NODE *oHead)
  {
      int fd[10][2];  // file descriptors' array
      int nfdCnt = 0 ;    // file descriptors counter
      string strCmd;      // command
      string strOp = "";  // operator
      int nOpCnt = 0 ;    // operator count
  
      while(1)
      {
          if (cHead != NULL)  // cHead is head pointer to the linked list of commands.
          {
              strCmd =  GetCmdOROperator(&amp;cHead); // get command
          }
          if (oHead == NULL)  // oHead is head pointer to the linked list of operators.
          {
              strOp = "";
          }
          else
          {
              strOp = GetCmdOROperator(&amp;oHead);   // get operator
          }
  
          if (strOp.empty())  // no operator exists. single or last command in the chain.
          {
              // Fork the child process
              pid_t child_id = fork();
  
              if(child_id == 0)
              {
                  // Execute the command
  
                  if (nOpCnt) // if we previously encountered any operator
                  {
                      close(fd[nfdCnt-1][FD_WRITE]);
                      dup2(fd[nfdCnt-1][FD_READ], FD_READ);   // read from pipe updated by previous command
                  }
  
                  // call execvp()
  
                  exit(-1);
              }
              else
              {
                  for (int i = 0 ; i &lt; nfdCnt; i++)
                  {
                      close(fd[nfdCnt][0]);
                      close(fd[nfdCnt][1]);
                  }
                  wait(NULL);
                  break;
              }
          }
  
          if (strOp == "|")
          {
              nOpCnt++ ;
  
              if (pipe (fd[nfdCnt]) &lt; 0)
              {
                  printf("\npipe error");
                  return ;
              }
  
              pid_t child_id = fork();
              if (child_id == 0)
              {
                  close(fd[nfdCnt][FD_READ]); // we dont need this
                  dup2(fd[nfdCnt][FD_WRITE], FD_WRITE);
  
                  if(nOpCnt &gt; 1) // if we have already encountered a pipe before
                  {
                      dup2(fd[nfdCnt-1][FD_READ],FD_READ);
                      close(fd[nfdCnt-1][FD_WRITE]);
                  }
  
                  // call execvp()
                  exit (-1);
              }
              else
              {
                  nfdCnt++;
              }
  
          }
  
      }
  }
  </code></pre>