import os

print "I'm going to fork now."
print "The child will write something to a pipe,"
print "and the parent will read it back."

r, w = os.pipe() # these are file descriptors, not file objects
r = os.fdopen(r, 'r', 0) # turn r into a file object
w = os.fdopen(w, 'w', 0)

pid = os.fork()

if pid:     # we are the parent
    w.close() # use os.close() to close a file descriptor
    print "parent: reading"
    text = r.read()
    print "parent: got it; text =", text
    os.wait() # wait for child to terminate
else:       # we are the child
    r.close()
    print "child: writing"
    w.write("here's some text from the child")
    w.close()
    print "child: closing"

