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

(yzsuai) #1
[...]$ ps -f
UID PID PPID C STIME TTY TIME CMD
5693094 20515 30778 0 04:43 pts/0 00:00:00 python fork-server.py
5693094 21646 20515 0 04:44 pts/0 00:00:00 [python] <defunct>
5693094 21813 30778 0 04:44 pts/0 00:00:00 ps -f
5693094 30778 30772 0 04:23 pts/0 00:00:00 -bash

In fact, if you type fast enough, you can actually see a child process morph from a real
running program into a zombie. Here, for example, a child spawned to handle a new
request changes to on exit. Its connection cleans up lingering zombies, and
its own process entry will be removed completely when the next request is received:


[...]$
Server connected by ('72.236.109.185', 58676) at Sun Apr 25 04:48:22 2010
[...] ps -f
UID PID PPID C STIME TTY TIME CMD
5693094 20515 30778 0 04:43 pts/0 00:00:00 python fork-server.py
5693094 27120 20515 0 04:48 pts/0 00:00:00 python fork-server.py
5693094 27174 30778 0 04:48 pts/0 00:00:00 ps -f
5693094 30778 30772 0 04:23 pts/0 00:00:00 -bash
[...]$ ps -f
UID PID PPID C STIME TTY TIME CMD
5693094 20515 30778 0 04:43 pts/0 00:00:00 python fork-server.py
5693094 27120 20515 0 04:48 pts/0 00:00:00 [python] <defunct>
5693094 27234 30778 0 04:48 pts/0 00:00:00 ps -f
5693094 30778 30772 0 04:23 pts/0 00:00:00 -bash

Preventing zombies with signal handlers on Linux


On some systems, it’s also possible to clean up zombie child processes by resetting the
signal handler for the SIGCHLD signal delivered to a parent process by the operating
system when a child process stops or exits. If a Python script assigns the SIG_IGN (ignore)
action as the SIGCHLD signal handler, zombies will be removed automatically and im-
mediately by the operating system as child processes exit; the parent need not issue
wait calls to clean up after them. Because of that, this scheme is a simpler alternative
to manually reaping zombies on platforms where it is supported.


If you’ve already read Chapter 5, you know that Python’s standard signal module lets
scripts install handlers for signals—software-generated events. By way of review, here
is a brief bit of background to show how this pans out for zombies. The program in
Example 12-5 installs a Python-coded signal handler function to respond to whatever
signal number you type on the command line.


Example 12-5. PP4E\Internet\Sockets\signal-demo.py


"""
Demo Python's signal module; pass signal number as a command-line arg, and use
a "kill -N pid" shell command to send this process a signal; on my Linux machine,
SIGUSR1=10, SIGUSR2=12, SIGCHLD=17, and SIGCHLD handler stays in effect even if
not restored: all other handlers are restored by Python after caught, but SIGCHLD
behavior is left to the platform's implementation; signal works on Windows too,
but defines only a few signal types; signals are not very portable in general;


Handling Multiple Clients | 809
Free download pdf