Example 5-19. PP4E\System\Processes\pipe1.py
import os, time
def child(pipeout):
zzz = 0
while True:
time.sleep(zzz) # make parent wait
msg = ('Spam %03d' % zzz).encode() # pipes are binary bytes
os.write(pipeout, msg) # send to parent
zzz = (zzz+1) % 5 # goto 0 after 4
def parent():
pipein, pipeout = os.pipe() # make 2-ended pipe
if os.fork() == 0: # copy this process
child(pipeout) # in copy, run child
else: # in parent, listen to pipe
while True:
line = os.read(pipein, 32) # blocks until data sent
print('Parent %d got [%s] at %s' % (os.getpid(), line, time.time()))
parent()
If you run this program on Linux, Cygwin, or another Unix-like platform (pipe is avail-
able on standard Windows Python, but fork is not), the parent process waits for the
child to send data on the pipe each time it calls os.read. It’s almost as if the child and
parent act as client and server here—the parent starts the child and waits for it to initiate
communication.# To simulate differing task durations, the child keeps the parent wait-
ing one second longer between messages with time.sleep calls, until the delay has
reached four seconds. When the zzz delay counter hits 005, it rolls back down to 000
and starts again:
[C:\...\PP4E\System\Processes]$ python pipe1.py
Parent 6716 got [b'Spam 000'] at 1267996104.53
Parent 6716 got [b'Spam 001'] at 1267996105.54
Parent 6716 got [b'Spam 002'] at 1267996107.55
Parent 6716 got [b'Spam 003'] at 1267996110.56
Parent 6716 got [b'Spam 004'] at 1267996114.57
Parent 6716 got [b'Spam 000'] at 1267996114.57
Parent 6716 got [b'Spam 001'] at 1267996115.59
Parent 6716 got [b'Spam 002'] at 1267996117.6
Parent 6716 got [b'Spam 003'] at 1267996120.61
Parent 6716 got [b'Spam 004'] at 1267996124.62
Parent 6716 got [b'Spam 000'] at 1267996124.62
#We will clarify the notions of “client” and “server” in the Internet programming part of this book. There,
we’ll communicate with sockets (which we’ll see later in this chapter are roughly like bidirectional pipes for
programs running both across networks and on the same machine), but the overall conversation model is
similar. Named pipes (fifos), described ahead, are also a better match to the client/server model because they
can be accessed by arbitrary, unrelated processes (no forks are required). But as we’ll see, the socket port
model is generally used by most Internet scripting protocols—email, for instance, is mostly just formatted
strings shipped over sockets between programs on standard port numbers reserved for the email protocol.
Interprocess Communication | 225