title: Emulating pipes
body: <p>I've just recently learned about pipes and I would like to emulate the "|" gimmick provided by shells.</p>
  
  <p>In the code below, the parent process spawns 2 child processes, after which they do their piping and get replaced by ls and grep. While that happens the parent process waits patiently. The problem is that the child processes never finish although they manage to send some data though the pipe and onto the screen.</p>
  
  <p>There are other posts regarding pipes on SO, but I've never seen the setup in which the parent process launches 2 children. I've only seen the parent communicating with one child.</p>
  
  <pre class="lang-c prettyprint-override"><code>int p0[2];
  pipe(p0);         //creating pipe
  
  if(fork() == 0) { //child 1
      dup2(p0[0], STDIN_FILENO);
      close(p0[0]); close(p0[1]);
      execlp("grep","grep","a",NULL);
  } 
  else {            //parent
      if(fork() == 0) { //child 2
          dup2(p0[1], STDOUT_FILENO);
          close(p0[0]); close(p0[1]);
          execlp("ls","ls",NULL);
      }
      else {    //parent
          wait(NULL);
          wait(NULL); //waiting for c1 and c2
  
          close(p0[0]); close(p0[1]);
          printf("parent exit\n");
      }
  }
  </code></pre>
  
  <p>My questions are: Why don't the child processes finish? Is fork-pipe structure sound or am I doing it completely wrong?</p>