[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

window and then the child is started in another. Messages start appearing in the parent
window only after the child is started and begins writing messages onto the fifo file:


[C:\...\PP4E\System\Processes] $ python pipefifo.py # parent window
Parent 8324 got "Spam 000" at 1268003696.07
Parent 8324 got "Spam 001" at 1268003697.06
Parent 8324 got "Spam 002" at 1268003699.07
Parent 8324 got "Spam 003" at 1268003702.08
Parent 8324 got "Spam 004" at 1268003706.09
Parent 8324 got "Spam 000" at 1268003706.09
Parent 8324 got "Spam 001" at 1268003707.11
Parent 8324 got "Spam 002" at 1268003709.12
Parent 8324 got "Spam 003" at 1268003712.13
Parent 8324 got "Spam 004" at 1268003716.14
Parent 8324 got "Spam 000" at 1268003716.14
Parent 8324 got "Spam 001" at 1268003717.15
...etc: Ctrl-C to exit...

[C:\...\PP4E\System\Processes]$ file /tmp/pipefifo # child window
/tmp/pipefifo: fifo (named pipe)

[C:\...\PP4E\System\Processes]$ python pipefifo.py -child
...Ctrl-C to exit...

Named pipe use cases


By mapping communication points to a file system entity accessible to all programs run
on a machine, fifos can address a broad range of IPC goals on platforms where they are
supported. For instance, although this section’s example runs independent programs,
named pipes can also be used as an IPC device by both in-process threads and directly
forked related processes, much as we saw for anonymous pipes earlier.


By also supporting unrelated programs, though, fifo files are more widely applicable to
general client/server models. For example, named pipes can make the GUI and
command-line debugger integration I described earlier for anonymous pipes even more
flexible—by using fifo files to connect the GUI to the non-GUI debugger’s streams, the
GUI could be started independently when needed.


Sockets provide similar functionality but also buy us both inherent network awareness
and broader portability to Windows—as the next section explains.


Sockets: A First Look


Sockets, implemented by the Python socket module, are a more general IPC device
than the pipes we’ve seen so far. Sockets let us transfer data between programs running
on the same computer, as well as programs located on remote networked machines.
When used as an IPC mechanism on the same machine, programs connect to sockets
by a machine-global port number and transfer data. When used as a networking con-
nection, programs provide both a machine name and port number to transfer data to
a remotely-running program.


236 | Chapter 5: Parallel System Tools

Free download pdf