title: using mkfifo to block on read until a write
body: <pre><code>gcc (GCC) 4.7.2
  c89
  </code></pre>
  
  <p>I am using pipes mkfifo. I have a reader and a writer.</p>
  
  <p>I want the reader to block until there is something in the file. </p>
  
  <p>There is a flag you can set O_NONBLOCK which is for non-blocking mode. So by default it should block on the read.</p>
  
  <p>Writing to the file</p>
  
  <pre><code>int main(void)
  {
      int fd;
      const char *pipe_file = "../../pipe_file/file";
      const char *pipe_msg = "PIPE Message";
  
      LOG_INFO("Start writer");
  
      /* Create the FIFO named pipe with read/write permissions */
      mkfifo(pipe_file, 0666);
  
      /* Write to the pipe */
      fd = open(pipe_file, O_WRONLY);
      write(fd, pipe_msg, strlen(pipe_msg) + 1);
  
      LOG_INFO("Terminate writer");
  
      return 0;
  }
  </code></pre>
  
  <p>Reading from the file</p>
  
  <pre><code>int main(void)
  {
      int fd = -1;
      const char *pipe_file = "../../pipe_file/file";
  #define BUF_SIZE 1024
      char rd_buffer[BUF_SIZE];
  
      LOG_INFO("Start reader");
  
      fd = open(pipe_file, O_RDONLY);
  
      do {
          memset(rd_buffer, 0, sizeof(rd_buffer));
      /* I WANT IT TO BLOCK HERE, UNTIL THE FILE IS WRITTEN AGAIN */
          read(fd, rd_buffer, sizeof(rd_buffer));
          LOG_INFO("Contents of buffer [ %s ]", rd_buffer);
      /* NO NEED TO SLEEP AS THE FILE WILL DELAY WHEN BLOCKING, I THINK */
      } while(1);
  
      /* We're done clean up */
      close(fd);
      unlink(pipe_file);
  
      LOG_INFO("Terminate reader");
  
      return 0;
  }
  </code></pre>