title: Reading named pipe does not flush it
body: <p>This is my first test on using unix named pipes. Below is a simple example which tries to read a given pipe every second and, on success, outputs "triggered" to stdout. Using a bash script I can write that value to the pipe which is read by the program as expected.</p>
  
  <p>The problem is, that the program keeps reading the value on every following loop although it is only written once to the pipe. Every tutorial I could find tells me, everything which is read from the pipe is basically removed and if one wants to flush a pipe simply read everything. But the program below keeps outputting the value over and over without new input.</p>
  
  <p><strong>main.cpp</strong></p>
  
  <pre class="lang-cpp prettyprint-override"><code>// std
  #include &lt;iostream&gt;
  // unix
  #include &lt;unistd.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  
  
  int main(int argc, char* argv[]) {
  
      // create named pipe
      mkfifo("/tmp/alarm_motion", 0666);
  
      for(;;){
  
          int fifo = open("/tmp/alarm_motion", O_RDONLY | O_NONBLOCK);
          char temp[sizeof(int)];
          int st = read(fifo, temp, sizeof(temp));
          if(st == 0){
              int res = atoi(temp);
              std::cout &lt;&lt; "fifo" &lt;&lt; res;
              if(res == 1){
                  std::cout &lt;&lt; " -&gt; triggered";
                      close(fifo);
              }
              std::cout &lt;&lt; std::endl;
          }
          sleep(1);
      }
  }
  </code></pre>
  
  <p><strong>test.sh</strong></p>
  
  <pre><code>#!/bin/bash
  pipe=/tmp/alarm_motion
  echo 1 &gt; $pipe
  </code></pre>
  
  <p>If I compile the program, start it, and execute the script after a few cycles, I receive the output below </p>
  
  <p><strong>sample output</strong></p>
  
  <pre><code>fifo0
  fifo0
  fifo0
  fifo0
  fifo0
  fifo0
  fifo1 -&gt; triggered
  fifo1 -&gt; triggered
  fifo1 -&gt; triggered
  fifo1 -&gt; triggered
  fifo1 -&gt; triggered
  fifo1 -&gt; triggered
  </code></pre>
  
  <p>while I would expect the following output</p>
  
  <p><strong>desired output</strong></p>
  
  <pre><code>fifo0
  fifo0
  fifo0
  fifo0
  fifo0
  fifo0
  fifo1 -&gt; triggered
  fifo0
  fifo0
  fifo0
  fifo0
  fifo0
  </code></pre>
  
  <p>Can somebody tell me what I am doing wrong here?</p>
  
  <p><em>g++ (Raspbian 4.9.2-10) on Raspbian 8</em></p>