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

(yzsuai) #1
[6476] => 2
[6684] => 2
...more output omitted...

The output of all of these processes shows up on the same screen, because all of them
share the standard output stream (and a system prompt may show up along the way,
too). Technically, a forked process gets a copy of the original process’s global memory,
including open file descriptors. Because of that, global objects like files start out with
the same values in a child process, so all the processes here are tied to the same single
stream. But it’s important to remember that global memory is copied, not shared; if a
child process changes a global object, it changes only its own copy. (As we’ll see, this
works differently in threads, the topic of the next section.)


The fork/exec Combination


In Examples 5-1 and 5-2, child processes simply ran a function within the Python pro-
gram and then exited. On Unix-like platforms, forks are often the basis of starting
independently running programs that are completely different from the program that
performed the fork call. For instance, Example 5-3 forks new processes until we type
q again, but child processes run a brand-new program instead of calling a function in
the same file.


Example 5-3. PP4E\System\Processes\fork-exec.py


"starts programs until you type 'q'"


import os


parm = 0
while True:
parm += 1
pid = os.fork()
if pid == 0: # copy process
os.execlp('python', 'python', 'child.py', str(parm)) # overlay program
assert False, 'error starting program' # shouldn't return
else:
print('Child is', pid)
if input() == 'q': break


If you’ve done much Unix development, the fork/exec combination will probably look
familiar. The main thing to notice is the os.execlp call in this code. In a nutshell, this
call replaces (overlays) the program running in the current process with a brand new
program. Because of that, the combination of os.fork and os.execlp means start a new
process and run a new program in that process—in other words, launch a new program
in parallel with the original program.


182 | Chapter 5: Parallel System Tools

Free download pdf