title: Detect when a fifo is opened from a program
body: <p>I have a situation where I need to check if the other side of a fifo has opened it, however I can't use a open because otherwise the program will start doing stuff.</p>
  
  <p>Why I have to do this: I have a program (a monitor) that launches a server program (both created by me). The monitor uses this fifo to communicate beacause the monitor can be closed/reopened while the server is already started.</p>
  
  <p>The problem is when the monitor starts the server: in this case I have to wait in some way for fifos to be created and then open them.
  Actually I'm using a while on the monitor that checks when the fifos are created, however in this way it opens the fifos <strong>before</strong> the server could do it (even if the instruction after the mkfifo is actually the open!!!).</p>
  
  <p>You may say that I'm opening the fifos in wrong order on the monitor (I'm opening the Write fifo(WRONLY) before the read fifo), the problem is that I can't revert this order because it's required that the server will wait for clients on the open (RDONLY) fifo.</p>
  
  <p>Any suggestion on how to avoid this race condition?
  I'm actually using a sleep in the monitor after checking if fifos are created, this obviusly solves the problem but I think is definitely not correct.</p>
  
  <p>Thanks to everyone</p>
  
  <p><strong>Edit 1:</strong></p>
  
  <p>This is how things are working at the moment</p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>mkfifo(fifo1)
  mkfifo(fifo2)
  open(fifo1 O_RDONLY)
  open(fifo2 O_WRONLY)
  </code></pre>
  
  <p><strong>Monitor</strong></p>
  
  <pre><code>while (fifo1 doesn't exists &amp;&amp; fifo2 doesn't exists);
  open(fifo1 O_WRONLY)
  open(fifo2 O_RDONLY)
  </code></pre>
  
  <p>I think the race condition is quite explicit now, it's important to notice that fifos are blocking (only RDONLY are blocking, WRONLY will not block even if there isn't anyone on the other side => <strong>this is a unix behaviour, not designed by me</strong>).</p>
  
  <p><strong>Edit 2:</strong></p>
  
  <p>The race condition happens at first fifo open level. <strong>I must open the first fifo on the server before the monitor does it.</strong></p>