title: how does synchronization work in this example?
body: <p>I am trying to implement pipe system call as part of my semester project.</p>
  
  <p>I came across the following code <a href="http://www.tutorialspoint.com/unix_system_calls/pipe.htm" rel="nofollow">here</a></p>
  
  <pre><code>#include &lt;sys/wait.h&gt;
  #include &lt;assert.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;string.h&gt;
  
  int
  main(int argc, char *argv[])
  {
      int pfd[2];
      pid_t cpid;
      char buf;
      assert(argc == 2);
  
      if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }
  
  
      cpid = fork();
      if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
  
      if (cpid == 0) {    /* Child reads from pipe */
          close(pfd[1]);          /* Close unused write end */
  
          while (read(pfd[0], &amp;buf, 1) &gt; 0)
              write(STDOUT_FILENO, &amp;buf, 1);
  
          write(STDOUT_FILENO, "\n", 1);
          close(pfd[0]);
          _exit(EXIT_SUCCESS);
  
      } else {            /* Parent writes argv[1] to pipe */
          close(pfd[0]);          /* Close unused read end */
          write(pfd[1], argv[1], strlen(argv[1]));
          close(pfd[1]);          /* Reader will see EOF */
          wait(NULL);             /* Wait for child */
          exit(EXIT_SUCCESS);
      }
  }
  </code></pre>
  
  <p>Having studied Multiprocessor programming, I realize this is a producer consumer model. The main process is forking a child which is consuming the bytes written by the main process in the write end of the pipe.</p>
  
  <p>I am not able to understand how the synchronization is working here. I mean how does the parent notify the child that it has written n number of bytes in the write end of the pipe?</p>
  
  <p>Does closing unused fd's has anything to do with synchronization?</p>
  
  <p>What if in this example, I want child to write something in the write end and parent to read it?</p>
  
  <p>Any help would be great, thanks!</p>