unix pipes + python

Cedric Adjih adjih-spam at crepuscule.com
Fri Dec 29 07:04:17 EST 2000


Timothy Docker <timd at macquarie.com.au> wrote:

> I must be doing something silly here...
>
> | import os
> | 
> | def child( infd  ) :
> |     "Run a child process"
> |     pid = os.fork()
> |     if pid == 0:
> |         if infd != None: os.dup2( infd, 0 )
> |         os.execv( '/usr/bin/cat', ['cat']  )
> |     else:
> | 	return pid
> | 
> | toPipe,fromPipe = os.pipe()
> | child( fromPipe )
> | os.write( toPipe, "hello\nthere\n" )
> | os.close( toPipe )
>
> This script behavious almost as expected. I end up with the text
> echoed back, but the 'cat' subprocess is left running - I was
> expecting it to exit when the write side of the pipe was closed in the 
> parent, but it is still reading from fd 0.
>
> Any suggestions on what's wrong?

According to Python it should be:
  fromPipe,toPipe = os.pipe()
You are reading and writing on the wrong descriptor of the pair.

Also closing the unused descriptor might be good style
(closing `fromPipe' in the parent, and `toPipe' in the child).

-- Cedric.



More information about the Python-list mailing list