title: Implementing piping in c++
body: <p>I'm trying to implement piping in C++. My method <code>piped</code> takes in an array of arguments along the line of <code>yes | head -10 | wc</code>. It creates pipes number of processes and changes the image of the processes to, following that example, <code>yes</code>, <code>head -10</code>, and <code>wc</code>. Then it creates pipes-2 pipes and redirects the input and output of the processes to the pipes.</p>
  
  <p>It's not working correctly, and just prints each command separately without redirecting input/output. </p>
  
  <pre><code>#include "piped.h"
  
  using namespace std;
  
  void piped(char *stringList[], int pipes)
  {
  
  //stringList[] is list of arguments seperated by |
  //pipes = number of arguments
  
  pid_t processList[256];
  char *curList[256];
  
  //Create a new process for each job using fork
  
  for(int i = 0; i &lt; pipes; i++){
      processList[i] = fork();
  
      if (processList[i] &lt; 0) {
          cerr &lt;&lt; "Couldn't create process\n";
          exit(1);
      }
  }
  
  int j = 0;
  
  //Replace the image of each process with the appropriate commands
  
  for(int i = 0; i &lt; pipes; i++){
  
      pid_t pid = processList[i];
  
      if(pid == 0){
  
      char *check = stringList[j];
  
      int k = 0;
  
      while(true){
  
          curList[k] = check;
          j+=1;
          k+=1;
  
          check = stringList[j];
  
          if(check == NULL || strcmp(check, "|") == 0){
              break;
          }
      }
  
      j+=1;
  
      curList[k] = NULL;
  
      execvp(curList[0], curList);
      cout &lt;&lt; "Exec error!\n";
      exit(1);
  
      }
  }
  
  
  //Piping
  //create n-2 pipes 
  //redirect the output of job i to the write end of pipe i
  //redirect the input of job i to the read end of pipe i
  
  for(int i = 0; i &lt; pipes-1; i++){
  
      int pipefd[2];
  
      if(pipe(pipefd) &lt; 0){
          cout &lt;&lt; "Pipe error!\n";
      }
  
      int pid1 = processList[i];
      int pid2 = processList[i+1];
  
      if(0 == pid2){
          //Child 2
          close(pipefd[1]);
          dup2(pipefd[0],1);
          close(pipefd[0]);
  
      }
  
      if(0 == pid1){
          close(pipefd[0]);
          dup2(pipefd[1], 0);
          close(pipefd[1]);
      }
  
  }
  
  //Wait for all jobs to terminate
  
  for(int i = 0; i &lt; pipes; i++){
      pid_t pid = processList[i];
      waitpid(pid, NULL, 0);
  }
  }
  </code></pre>