Named pipe basics
In Python, named pipe files are created with the os.mkfifo call, which is available today
on Unix-like platforms, including Cygwin’s Python on Windows, but is not currently
available in standard Windows Python. This call creates only the external file, though;
to send and receive data through a fifo, it must be opened and processed as if it were a
standard file.
To illustrate, Example 5-24 is a derivation of the pipe2.py script listed in Exam-
ple 5-20, but rewritten here to use fifos rather than anonymous pipes. Much like
pipe2.py, this script opens the fifo using os.open in the child for low-level byte string
access, but with the open built-in in the parent to treat the pipe as text; in general, either
end may use either technique to treat the pipe’s data as bytes or text.
Example 5-24. PP4E\System\Processes\pipefifo.py
"""
named pipes; os.mkfifo is not available on Windows (without Cygwin);
there is no reason to fork here, since fifo file pipes are external
to processes--shared fds in parent/child processes are irrelevent;
"""
import os, time, sys
fifoname = '/tmp/pipefifo' # must open same name
def child():
pipeout = os.open(fifoname, os.O_WRONLY) # open fifo pipe file as fd
zzz = 0
while True:
time.sleep(zzz)
msg = ('Spam %03d\n' % zzz).encode() # binary as opened here
os.write(pipeout, msg)
zzz = (zzz+1) % 5
def parent():
pipein = open(fifoname, 'r') # open fifo as text file object
while True:
line = pipein.readline()[:-1] # blocks until data sent
print('Parent %d got "%s" at %s' % (os.getpid(), line, time.time()))
if name == 'main':
if not os.path.exists(fifoname):
os.mkfifo(fifoname) # create a named pipe file
if len(sys.argv) == 1:
parent() # run as parent if no args
else: # else run as child process
child()
Because the fifo exists independently of both parent and child, there’s no reason to fork
here. The child may be started independently of the parent as long as it opens a fifo file
by the same name. Here, for instance, on Cygwin the parent is started in one shell
Interprocess Communication | 235