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

(yzsuai) #1

connection, address = sockobj.accept() # pass to process for service
print('Server connected by', address, end=' ')
print('at', now())
childPid = os.fork() # copy this process
if childPid == 0: # if in child process: handle
handleClient(connection) # else: go accept next connect


dispatcher()


Where applicable, this technique is:



  • Much simpler; we don’t need to manually track or reap child processes.

  • More accurate; it leaves no zombies temporarily between client requests.


In fact, only one line is dedicated to handling zombies here: the signal.signal call near
the top, to set the handler. Unfortunately, this version is also even less portable than
using os.fork in the first place, because signals may work slightly differently from plat-
form to platform, even among Unix variants. For instance, some Unix platforms may
not allow SIG_IGN to be used as the SIGCHLD action at all. On Linux systems, though,
this simpler forking server variant works like a charm:


[...]$ python fork-server-signal.py &
[1] 3837
Server connected by ('72.236.109.185', 58817) at Sun Apr 25 08:11:12 2010

[...] ps -f
UID PID PPID C STIME TTY TIME CMD
5693094 3837 30778 0 08:10 pts/0 00:00:00 python fork-server-signal.py
5693094 4378 3837 0 08:11 pts/0 00:00:00 python fork-server-signal.py
5693094 4413 30778 0 08:11 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 3837 30778 0 08:10 pts/0 00:00:00 python fork-server-signal.py
5693094 4584 30778 0 08:11 pts/0 00:00:00 ps -f
5693094 30778 30772 0 04:23 pts/0 00:00:00 –bash

Notice how in this version the child process’s entry goes away as soon as it exits, even
before a new client request is received; no “defunct” zombie ever appears. More dra-
matically, if we now start up the script we wrote earlier that spawns eight clients in
parallel (testecho.py) to talk to this server remotely, all appear on the server while run-
ning, but are removed immediately as they exit:


[client window]
C:\...\PP4E\Internet\Sockets> testecho.py learning-python.com

[server window]
[...]$
Server connected by ('72.236.109.185', 58829) at Sun Apr 25 08:16:34 2010
Server connected by ('72.236.109.185', 58830) at Sun Apr 25 08:16:34 2010
Server connected by ('72.236.109.185', 58831) at Sun Apr 25 08:16:34 2010
Server connected by ('72.236.109.185', 58832) at Sun Apr 25 08:16:34 2010

812 | Chapter 12: Network Scripting

Free download pdf