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

(yzsuai) #1

mypid = os.getpid()
spawn('python', 'pipes-testchild.py', 'spam') # fork child program


print('Hello 1 from parent', mypid) # to child's stdin
sys.stdout.flush() # subvert stdio buffering
reply = input() # from child's stdout
sys.stderr.write('Parent got: "%s"\n' % reply) # stderr not tied to pipe!


print('Hello 2 from parent', mypid)
sys.stdout.flush()
reply = sys.stdin.readline()
sys.stderr.write('Parent got: "%s"\n' % reply[:-1])


The spawn function in this module does not work on standard Windows Python (re-
member that fork isn’t yet available there today). In fact, most of the calls in this module
map straight to Unix system calls (and may be arbitrarily terrifying at first glance to
non-Unix developers!). We’ve already met some of these (e.g., os.fork), but much of
this code depends on Unix concepts we don’t have time to address well in this text.
But in simple terms, here is a brief summary of the system calls demonstrated in this
code:


os.fork
Copies the calling process as usual and returns the child’s process ID in the parent
process only.


os.execvp
Overlays a new program in the calling process; it’s just like the os.execlp used
earlier but takes a tuple or list of command-line argument strings (collected with
the *args form in the function header).


os.pipe
Returns a tuple of file descriptors representing the input and output ends of a pipe,
as in earlier examples.


os.close(fd)
Closes the descriptor-based file fd.


os.dup2(fd1,fd2)
Copies all system information associated with the file named by the file descriptor
fd1 to the file named by fd2.


In terms of connecting standard streams, os.dup2 is the real nitty-gritty here. For ex-
ample, the call os.dup2(parentStdin,stdinFd) essentially assigns the parent process’s
stdin file to the input end of one of the two pipes created; all stdin reads will henceforth
come from the pipe. By connecting the other end of this pipe to the child process’s copy
of the stdout stream file with os.dup2(childStdout,stdoutFd), text written by the child
to its sdtdout winds up being routed through the pipe to the parent’s stdin stream. The
effect is reminiscent of the way we tied together streams with the subprocess module
in Chapter 3, but this script is more low-level and less portable.


230 | Chapter 5: Parallel System Tools

Free download pdf