This is what I would make of it;
from __future__ import print_function #(1)
import os #(2)
import sys
import time
def child(pipein): # (3)
num1 = int(os.read(pipein, 32)) # (6)
num2 = int(os.read(pipein, 32))
r = num1 * num2
print("r = {}".format(r))
print("Child says bye.")
sys.stdout.flush() # (4)
os._exit(0) # (5)
def parent():
pipein, pipeout = os.pipe()
x = 1
if os.fork() == 0:
print("Launching child")
child(pipein)
else: # (7)
print("In parent")
num1 = str(2) # (8)
num2 = str(1)
os.write(pipeout, num1)
os.write(pipeout, num2)
print("Parent goes to sleep")
time.sleep(x)
print("Parent says bye.")
if __name__ == '__main__':
parent()
- This is required to make the
print()
function work in Python 2.x - Style: imports should each be on a separate line
- No need for a loop if you're going to
exit()
after the first iteration - Otherwise the print might not show up.
- Style: use two blank lines after a function.
- Style: use a space after a comma, unless it's at the end of a line.
- Remove the while loop, or you'll be in an infinite loop.
- Style: use spaces around operators.
With these modifications I get the following output;
In parent
Launching child
Parent goes to sleep
r = 2
Child says bye.
Parent says bye.
If you want to use multiple processes, it is generally a much better idea to use the multiprocessing
module. It has objects for processes and process pools, and communication objects like queues and pipes. Queues are first-in first-out, and they are synchronized; so if you put two items in, you can read two items.