#################################################
#https://maths.nuigalway.ie/~gettrick/teach/cs211/
#################################################
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') # turn r into a file object
w = os.fdopen(w, 'w')

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()
    r.close()
    print ("parent: got it; text =", text)
    os.wait() # wait for child to terminate
else:       # we are the child
    r.close()
    print ("child: writing")
    text = "here's some text from the child"
    w.write(text)
    w.close()
    print ("child: closing")

