title: C++ Linux Shell - Using Pipes, Fork, and Exec over a Command Vector
body: <p>I'm writing a shell for Linux in C++. My main concern is being able to pipe commands indefinitely. Example:</p>
  
  <pre><code>ls | cat -A | cat -A | cat -A
  </code></pre>
  
  <p>To do this, I've parsed the input string and made several unix_command objects and push_backed them into a vector. The unix_command struct provides the information needed to run the command, like its name and args.</p>
  
  <p>I need to loop over the vector, set up the pipes so that the current process gets input from the previous process, and continue until the end of the vector. I am doing this with a for-loop and a bunch of dup2 commands, but with no luck. As of now I am getting weird infinite-looping behavior.</p>
  
  <pre><code>if(cmdVector.size() &gt; 1){
  
          int filedes[2]; // filedes[0] is for reading, filedes[1] is for writing.
          pipe(filedes);  //Makes a pipe
  
          //STARTING OVER ON PIPING
          dup2(0,filedes[1]); // Sets write end of pipe to standard input (keyboard)
  
          for(unsigned int i = 0; i &lt; cmdVector.size(); i++){
              //Do the piping, fork, and run() operations in here!!
              pid_t pid = fork();
              if(pid == 0){   //Child
                  if(i != cmdVector.size() - 1){  //As long as this isn't the last command
                      dup2(filedes[WRITE],1); //Set writes of the process here
                      close(filedes[READ]);
                      close(filedes[WRITE]);
                  }
                  cmdVector[i].run(); //Runs command and calls exec
  
  
              }
              else{
                  wait(NULL);
                  dup2(filedes[READ],0);  //Set input of the main process here, because it forks into the next process, right?
                  close(filedes[READ]);   //So if this loops back around and forks, will the child still have the pipe as its input?
                  close(filedes[WRITE]);
              }
          }
          dup2(0,0);  //Resets read and write back to normal, hopefully
          dup2(1,1);
      }
      else{   //Just one process, no piping
          pid_t pid = fork();
          if(pid == 0){   //Child
              cmdVector[0].run();
          }
          else{
              wait(NULL);
          }
  
      }
  </code></pre>
  
  <p>Any help is appreciated! Thank you!</p>
  
  <p>Full shell.cpp file if you'd like to run it: <a href="https://drive.google.com/open?id=0BwN_NTSpWmSzWmMzVEl0UzNDZEk" rel="nofollow noreferrer">https://drive.google.com/open?id=0BwN_NTSpWmSzWmMzVEl0UzNDZEk</a></p>
  
  <p>MakeFile: <a href="https://drive.google.com/open?id=0BwN_NTSpWmSzTVNSdWxSQWJzYzA" rel="nofollow noreferrer">https://drive.google.com/open?id=0BwN_NTSpWmSzTVNSdWxSQWJzYzA</a></p>