Spawned child program
Just as when typed at a shell, the string of arguments passed to os.execlp by the fork-
exec script in Example 5-3 starts another Python program file, as shown in Example 5-4.
Example 5-4. PP4E\System\Processes\child.py
import os, sys
print('Hello from child', os.getpid(), sys.argv[1])
Here is this code in action on Linux. It doesn’t look much different from the original
fork1.py, but it’s really running a new program in each forked process. More observant
readers may notice that the child process ID displayed is the same in the parent program
and the launched child.py program; os.execlp simply overlays a program in the same
process:
[C:\...\PP4E\System\Processes]$ python fork-exec.py
Child is 4556
Hello from child 4556 1
Child is 5920
Hello from child 5920 2
Child is 316
Hello from child 316 3
q
There are other ways to start up programs in Python besides the fork/exec combination.
For example, the os.system and os.popen calls and subprocess module which we ex-
plored in Chapters 2 and 3 allow us to spawn shell commands. And the os.spawnv call
and multiprocessing module, which we’ll meet later in this chapter, allow us to start
independent programs and processes more portably. In fact, we’ll see later that multi
processing’s process spawning model can be used as a sort of portable replacement for
os.fork in some contexts (albeit a less efficient one) and used in conjunction with the
os.exec* calls shown here to achieve a similar effect in standard Windows Python.
We’ll see more process fork examples later in this chapter, especially in the program
exits and process communication sections, so we’ll forego additional examples here.
We’ll also discuss additional process topics in later chapters of this book. For instance,
forks are revisited in Chapter 12 to deal with servers and their zombies—dead processes
lurking in system tables after their demise. For now, let’s move on to threads, a subject
which at least some programmers find to be substantially less frightening...
184 | Chapter 5: Parallel System Tools