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:
--------------------------------------------------------------------------------
#!/usr/bin/python
import os, sys
r, w = os.pipe()
write = os.fdopen(w, 'w')
print >> write, "foo"
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
sys.exit(0)
write.close()
read = os.fdopen(r)
print read.read()
read.close()
--------------------------------------------------------------------------------
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,
--------------------------------------------------------------------------------
#include