title: Does this multiple pipes code in C makes sense?
body: <p>I've created a <a href="https://stackoverflow.com/questions/916900/having-trouble-with-fork-pipe-dup2-and-exec-in-c/">question about this a few days</a>. My solution is something in the lines of what was suggested in the accepted answer. However, a friend of mine came up with the following solution:</p>
  
  <p>Please note that the code has been updated a few times (check the edit revisions) to reflect the suggestions in the answers below. If you intend to give a new answer, please do so with this new code in mind and not the old one which had lots of problems.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char *argv[]){
      int fd[2], i, aux, std0, std1;
  
      do {
          std0 = dup(0); // backup stdin
          std1 = dup(1); // backup stdout
  
          // let's pretend I'm reading commands here in a shell prompt
          READ_COMMAND_FROM_PROMPT();
  
          for(i=1; i&lt;argc; i++) {
              // do we have a previous command?
              if(i &gt; 1) {
                  dup2(aux, 0);
                  close(aux);
              }
  
              // do we have a next command?
              if(i &lt; argc-1) {
                  pipe(fd);
  
                  aux = fd[0];
                  dup2(fd[1], 1);
                  close(fd[1]);
              }
  
              // last command? restore stdout...
              if(i == argc-1) {
                  dup2(std1, 1);
                  close(std1);
              }
  
              if(!fork()) {
                  // if not last command, close all pipe ends
                  // (the child doesn't use them)
                  if(i &lt; argc-1) {
                      close(std0);
                      close(std1);
                      close(fd[0]);
                  }
  
                  execlp(argv[i], argv[i], NULL);
                  exit(0);
              }
          }
  
          // restore stdin to be able to keep using the shell
          dup2(std0, 0);
          close(std0);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>This simulates a series of commands through pipes like in bash, for instance: cmd1 | cmd2 | ... | cmd_n. I say "simulate", because, as you can see, the commands are actually read from the arguments. Just to spare time coding a simple shell prompt...</p>
  
  <p>Of course there are some issues to fix and to add like error handling but that's not the point here. I think I kinda get the code but it still makes me a lot of confusing how this whole thing works.</p>
  
  <p>Am I missing something or this really works and it's a nice and clean solution to solve the problem? If not, can anyone point me the crucial problems this code has?</p>