title: C - How to detect EOF in pipe when reading only single char?
body: <p>As explained in <a href="https://stackoverflow.com/questions/22210534/why-does-the-read-end-of-a-pipe-read-eof-only-if-the-write-end-is-closed">this</a> answer, I'd be expecting the <strong>reader process</strong> to catch the <code>EOF</code> right after the <strong>writer process</strong> closes all related file descriptors. </p>
  
  <p>But that doesn't happen and this program ends up stuck in an endless loop.
  Parent waits for it's child to finish &amp; child waits for <code>EOF</code> signalizing closed pipe.</p>
  
  <h3>Why the reader process doesn't receive <code>EOF</code>?</h3>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;wait.h&gt;
  
  #define STRING_TO_SEND "Hello, world!\n"
  
  int main() {
      int fd[2], i = 0;
      __pid_t pid;
      char _char;
      ssize_t nbytes;
  
      pipe(fd);
      pid = fork();
  
      if (pid == -1) {
          // Error
          perror("Error forking!");
          return EXIT_FAILURE;
  
      } else if (pid == 0) {
  
          // Child
          close(fd[1]);
          while ((nbytes = read(fd[0], &amp;_char, 1)) != EOF) {
              if (nbytes == 0)
                  continue;
              putchar(_char);
          }
          close(fd[0]);
  
      } else {
  
          // Parent
          close(fd[0]);
  
          for(;;) {
              _char = STRING_TO_SEND[i++];
              write(fd[1], &amp;_char, 1);
              if (_char == '\0')
                  break;
          }
  
          close(fd[1]);
          close(STDOUT_FILENO);
  
          while (wait(NULL)&gt;0) {}
      }
      return 0;
  }
  </code></pre>