title: Piping Given an Array of UNIX Commands
body: <p>So I am at the very end of a project to create a basic UNIX shell using C.  I have finished a lot of different pieces of the program, but now I would like to conquer piping.  I would specifically like to create a program that can handle <strong>any number</strong> of pipes.</p>
  
  <p>For some reason my code get to s certain line (labeled: <strong>//DIES HERE</strong>) and then stops and I can't figure out why.</p>
  
  <p>Here is the code that I have so far:</p>
  
  <pre><code>//the contents of args[0] is {"ls","-l","-o"}
  //the contents of args[1] is {"wc","-l"}
  
  int pipefd[2];
  
  pipe(&amp;pipefd[0]);   // Error check!
  
  fflush(stdout);
  for (i = 0; i &lt; commands; i++){
      int pid = fork();
  
      if (pid == 0){
  
          int command_no = i;
          int prev_pipe = ((command_no - 1) % 2) * 2;
          int current_pipe = (command_no % 2) * 2;
          printf("\ncmd %d: prev pipe %d, curr pipe %d\n\n", i, prev_pipe, current_pipe);
          fflush(stdout);
  
          // 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 == commands - 1){
              close(pipefd[current_pipe + 1]);                    
          }
          else{
              dup2(pipefd[current_pipe + 1], 1); //DIES HERE
          }
          // printf("Here?\n\n");
          execvp(*args[i], args[i]);
          fprintf(stderr, "Failed to exec: %s (%d: %s)\n", arrayOfCommands[i], errno, strerror(errno));
          _exit(1);
      }
  }
  </code></pre>
  
  <p>Any help is appreciated! :)</p>