[Python-Dev] Forking and pipes

James Y Knight foom at fuhm.net
Tue Dec 9 20:40:11 CET 2008


On Dec 9, 2008, at 2:26 PM, Lars Kotthoff wrote:

> Dear list,
>
> I recently noticed a python program which uses forks and pipes for
> communication between the processes not behaving as expected. The  
> minimal
> example program:
>
> [snip]

> This prints out "foo" twice although it's only written once to the  
> pipe. It
> seems that python doesn't flush file descriptors before copying them  
> to the
> child process, thus resulting in the duplicate message. The  
> equivalent C
> program behaves as expected,
>
> [snip]
>
> Is this behaviour intentional? I've tested both python and C on  
> Linux, OpenBSD
> and Solaris (python versions 2.5.2 and 2.3.3), the behaviour was the  
> same
> everywhere.


Yes, it's intentional. And, no, your programs aren't equivalent.

Rewrite your C program to use fdopen, and fread/fwrite. *Then* it will  
be equivalent and have the same behavior as the python program.

Alternatively, you can change your python program to use os.read/ 
os.write instead of fdopen and fileobject.read/fileobject.write, if  
you want your python program to work like the C program.

James


More information about the Python-Dev mailing list