title: Python and FIFOs
body: <p>I was trying to understand FIFOs using Python under linux and I found a strange behavior i don't understand.</p>
  
  <p>The following is <code>fifoserver.py</code></p>
  
  <pre><code>import sys
  import time
  
  def readline(f):
      s = f.readline()
      while s == "":
          time.sleep(0.0001)
          s = f.readline()
      return s
  
  while True:
      f = open(sys.argv[1], "r")
      x = float(readline(f))
      g = open(sys.argv[2], "w")
      g.write(str(x**2) + "\n")
      g.close()
      f.close()
      sys.stdout.write("Processed " + repr(x) + "\n")
  </code></pre>
  
  <p>and this is <code>fifoclient.py</code></p>
  
  <pre><code>import sys
  import time
  
  def readline(f):
      s = f.readline()
      while s == "":
          time.sleep(0.0001)
          s = f.readline()
      return s
  
  def req(x):
      f = open("input", "w")
      f.write(str(x) + "\n")
      f.flush()
      g = open("output", "r")
      result = float(readline(g))
      g.close()
      f.close()
      return result
  
  for i in range(100000):
      sys.stdout.write("%i, %s\n" % (i, i*i == req(i)))
  </code></pre>
  
  <p>I also created two FIFOs using <code>mkfifo input</code> and <code>mkfifo output</code>.</p>
  
  <p>What I don't understand is why when I run the server (with <code>python fifoserver.py input output</code>) and the client (with <code>python fifoclient.py</code>) from two consoles after some requests the client crashes with a "broken pipe" error on <code>f.flush()</code>. Note that before crashing I've seen from a few hundreds to several thousands correctly processed requests running fine.</p>
  
  <p>What is the problem in my code?</p>