Python open a named pipe == hanging?

Donn Cave donn at u.washington.edu
Mon Aug 7 11:51:36 EDT 2006


In article <1hjk7cf.iswobo130hqzxN%aleax at mac.com>,
 aleax at mac.com (Alex Martelli) wrote:

> Donn Cave <donn at u.washington.edu> wrote:
> 
> > In article <op.tdp5i6tsh12lye at cadet.mshome.net>,
> >  Rochester <rochester1976 at gmail.com> wrote:
> > 
> > >      I just found out that the general open file mechanism doesn't work
> > >      for named pipes (fifo).  Say I wrote something like this and it
> > >      simply hangs python:
> > > 
> > > #!/usr/bin/python
> > > 
> > > import os
> > > 
> > > os.mkfifo('my fifo')
> > > 
> > > open('my fifo', 'r+').write('some strings.')
> > > x = os.popen('cat my fifo').read()
> > > 
> > > print x
> > 
> > I believe your problem is that, by the time you open the
> > pipe for read, it has already been closed by its writer.
> 
> Hmmm, no: the problem is, he never opens the pipe for write, because the
> open blocks (will not proceed until somebody opens the fifo for reading,
> which in turn won't happen here because the open blocks).
> 
> Try:
> 
> a = open('my_fifo', 'w')
> b = os.popen('cat my_fifo')
> a.write ...
> a.close()
> c = b.read()
> 
> this STILL doesn't work, since the very first statement blocks.  (I've
> also removed the 'r+' mode in favor of 'w', since opening a FIFO for
> reading AND writing produces undefined behavior, at least in all Unix
> versions and variants I'm familiar with).

But it does work.  I edited that excerpt only to complete
missing parts, and ran it on MacOS X and GNU Linux.

import os
f = '/tmp/r'
try:
        os.unlink(f)
except:
        pass
a = open(f, 'w')
b = os.popen('cat %s' % f)
a.write('chunks\n')
a.close()
c = b.read()
print repr(c)


> > it.  (You can't read "all" the data, though - since you still
> > have the file open, it has no end of file - so you can't
> > solve the problem exactly as stated above.)
> 
> Actually, in CPython (1.5.2 to 2.5 included, at least), _IF_ open worked
> normally then the file WOULD be closed by the statement
> 
> open('my fifo', 'r+').write('some strings.')

Sure, but now we're back to closing the pipe before the reader
gets to it.  That doesn't work.


   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list