title: How is this Producer & Consumer using pipes example able to prevent a deadlock?
body: <p>I'm taking a look at a Solution Example for Producer &amp; Consumer problem, using pipes. </p>
  
  <p>And I do not understand how it is preventing a race condition.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;string.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;sys/wait.h&gt;
  
  
  void producer(FILE *pipe_write_end)
  {
    int i;
    for(i = 1; i &lt;= 10; i++) {
      fprintf(pipe_write_end, "%d ", i);
    }
    fclose(pipe_write_end);
    exit(0);
  }
  
  
  void consumer(FILE *pipe_read_end)
  {
    int n,k;
  
    while(1) {
      int n = fscanf(pipe_read_end, "%d", &amp;k);
      if(n == 1) printf("consumer: got %d\n", k);
      else break;
    }
    fclose(pipe_read_end);
    exit(0);
  }
  
  
  int main()
  {
    pid_t producer_id, consumer_id;
    int pd[2];
    FILE *pipe_write_end, *pipe_read_end;
  
  
    pipe(pd);
    pipe_read_end  = fdopen(pd[0], "r");
    pipe_write_end = fdopen(pd[1], "w");
  
  
    producer_id = fork();
    if(producer_id == 0) {
        fclose(pipe_read_end);
      producer(pipe_write_end);
  
    }
  
    consumer_id = fork();
    if(consumer_id == 0) {
      fclose(pipe_write_end);
      consumer(pipe_read_end);
    }
  
    fclose(pipe_read_end);
    fclose(pipe_write_end);
    wait(NULL);
    wait(NULL);
  
    return 0;
  }
  </code></pre>
  
  <p>My current thinking is that the <code>int n = fscanf(pipe_read_end, "%d", &amp;k);</code> is waiting for the producer to close the file, but I don't understand how.</p>
  
  <p>If 2 Child Processes are created, 1 to consume, 1 to Produce
  - How is it able to automatically just produce without error?</p>