title: C++ pipes between multiple children
body: <p>I am working on a project and I got it mostly figured out except for one minor(big) problem. I can't seem to figure out how to create pipes between any number of children.</p>
  
  <p>for example I am taking in command line arguments to determine how many children will be produced. The first child doesn't have input but has output and the last child outputs to STD output. I  need to pass values into the first child and into each child after that in order. Here is what i got:</p>
  
  <pre><code>#include &lt;errno.h&gt;
  #include &lt;cstdio&gt;
  #include &lt;iostream&gt;
  #include &lt;sys/wait.h&gt;
  
  using namespace std;
  
  int main(int argc, char *argv[]) {
      pid_t childpid;
      int x2ypipe[2];
      pipe(x2ypipe);
      if(x2ypipe==0) {
          cout&lt;&lt;"ERROR:"&lt;&lt;errno&lt;&lt;endl;
      }
      int y2zpipe[2];
      pipe(y2zpipe);
      if(y2zpipe==0) {
          cout&lt;&lt;"ERROR:"&lt;&lt;errno&lt;&lt;endl;
      }
      pid_t xchild =fork();
      if(xchild==0) {
          dup2(x2ypipe[1],STDOUT_FILENO);
          close(x2ypipe[0]);
          close(x2ypipe[1]);
          int a=execl(argv[1],argv[1], (char*)NULL);
          if(a==-1) {
              perror("The following error occurred at A");
          }
      }
      for(int i=2; i&lt;(argc-1); i++) {
          childpid =fork();
          if(childpid==0) {
              dup2(x2ypipe[0],STDIN_FILENO);
              close(x2ypipe[0]);
              close(x2ypipe[1]);
              //direct y2z pipe to standard output and replace the child with the program part2
              dup2(x2ypipe[1],y2zpipe[1]);
              dup2(y2zpipe[1],STDOUT_FILENO);
              close(y2zpipe[0]);
              close(y2zpipe[1]);
              int b=execl(argv[i],argv[i],(char *)NULL);
              if(b==-1) {
                  perror("The following error occurred at B");
              }
          }
      }
      pid_t zchild =fork();
      if(zchild==0) {
          dup2(y2zpipe[0],STDIN_FILENO);
          close(y2zpipe[0]);
          close(y2zpipe[1]);
          int c=execl(argv[argc-1],argv[argc-1],(char *)NULL);
          if(c==-1) {
              perror("The following error occurred at C");
          }
      }
      close(x2ypipe[0]);
      close(x2ypipe[1]);
      wait(NULL);
      wait(NULL);
      wait(NULL);
  }
  </code></pre>
  
  <p>now right now I am only passing in three programs in to the argv[] and it works fine. I will have to add a if statement in my for loop to check for the last/highest possible value of i to connect the y2z pipe to the zchild. What I am having trouble doing it connecting the children to each other within the for loop. How would I go about creating a new pipe for each child from the last child?</p>