title: communicating between two child processes with pipes
body: <p>I'm trying to write code that spawns two child processes that send each other a message over a pipe then terminate. However, when I run the following code only child2 prints it's greeting but child 1 still prints the message it gets from child 2 where child 1 doesn't.</p>
  
  <p>Does anybody know what's wrong with my methodology?</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char** argv) {
      char chld_1_send[20] = "hello from child 1";
      char chld_1_recv[20];
      char chld_2_send[20] = "hi from child 2";
      char chld_2_recv[20];
  
      int chld_1_outgoing[2];
      int chld_2_outgoing[2];
  
      pipe(chld_1_outgoing);
      pipe(chld_2_outgoing);
  
      int chld_1_status, chld_2_status;
      pid_t chld_1, chld_2;
  
      chld_1 = fork();
  
      if(chld_1 == 0) {
          chld_2 = fork();
      }
  
      if(chld_1 == 0 &amp;&amp; chld_2 == 0) {
          printf("parent [pid:%d] waiting on both children to finish\n", getpid());
  
          while(wait(&amp;chld_1_status) != chld_1 &amp;&amp; wait(&amp;chld_2_status) != chld_2) {}
  
          printf("done waiting\n");
      }
      else if(chld_1 != 0 &amp;&amp; chld_2 == 0) {
          printf("this is child 1 [pid:%d] with parent [pid:%d]\n", getpid(), getppid());
  
          write(chld_1_outgoing[1], chld_1_send, strlen(chld_1_send));
          while(read(chld_1_outgoing[0], &amp;chld_1_recv, sizeof(chld_2_recv)) &lt; 0) {}
  
          printf("child 2 said '%s'\n", chld_1_recv);
          exit(0);
      }
      else if(chld_2 != 0 &amp;&amp; chld_1 == 0) {
          printf("this is child 2 [pid:%d] with parent [pid:%d]\n", getpid(), getppid());
  
          write(chld_2_outgoing[1], chld_2_send, strlen(chld_2_send));
          while(read(chld_2_outgoing[0], &amp;chld_2_recv, sizeof(chld_2_recv)) &lt; 0) {}
  
          printf("child 1 said '%s'\n", chld_2_recv);
  
          exit(0);
      }
  
      printf("both children have terminated successfully\n");
  
      return 0;
  }
  </code></pre>
  
  <p>However, running this command prints out this to the terminal and goes into an infinite loop:</p>
  
  <pre><code>$ this is child 2 [pid:15713] with parent [pid:1]
  child 1 said 'hi from child 2'
  parent [pid:15714] waiting on both children to finish
  </code></pre>