title: Writing my own shell... stuck on pipes?
body: <p>For the past few days I have been attempting to write my own shell implementation but I seem to have gotten stuck on getting pipes to work properly.  I am able to parse a line and fork off the commands between the pipes (ex: ls | sort) individually but can't seem to get them to pipe input from one into the other.</p>
  
  <p>I think I just don't understand how to use dup2() and pipes properly.  </p>
  
  <p>I've now included my code which is still failing... :(  So stuck...</p>
  
  <pre><code>void forkAndExecute( char* arrayOfWords[] , vector&lt;pid_t&gt; *vectorOfPIDs , bool hasNextCmd , bool hasPrevCmd) {
  
  int fd[ 2 ];
  pid_t pid;
  
  if( hasNextCmd ){
      pipe(fd);
  }
  
  pid = fork();
  
  //error if PID &lt; 0
  if( pid &lt; 0 ) {
      cerr &lt;&lt; "&gt;&gt;&gt; fork failed &gt;&gt;&gt;" &lt;&lt; endl;
      exit(-1);
  }
  //child process if PID == 0
  else if( pid == 0 ) {
      if ( hasPrevCmd ){
          dup2(fd[0] , 0);
          close(fd[0]);
          close(fd[1]);
  
      }
      if ( hasNextCmd ){
          dup2(fd[1],1);
          close(fd[0]);
          close(fd[1]);
      }
      execvp( arrayOfWords[0] , arrayOfWords );
      cout &lt;&lt; "&gt;&gt;&gt; command not found &gt;&gt;&gt;" &lt;&lt; endl;
      //if logic reaches here, exec failed
      exit(0);
  } 
  //parent process
  else{
      close(fd[0]);
      close(fd[1]);
      //if( ! isLastCmd ){
  
      //}
      vectorOfPIDs-&gt;push_back(pid);
  }
  </code></pre>
  
  <p>}</p>