8380 7336 8380 428 con 1004 18:26:50 /usr/bin/ps
$ kill −12 8224
Got signal 12 at Sun Mar 7 18:27:28 2010
$ kill −12 8224
Got signal 12 at Sun Mar 7 18:27:30 2010
$ kill −9 8224
[1]+ Killed python signal1.py 12
Inputs and outputs can be a bit jumbled here because the process prints to the same
screen used to type new shell commands. To send the program a signal, the kill shell
command takes a signal number and a process ID to be signaled (8224); every time a
new kill command sends a signal, the process replies with a message generated by a
Python signal handler function. Signal 9 always kills the process altogether.
The signal module also exports a signal.alarm function for scheduling a SIGALRM signal
to occur at some number of seconds in the future. To trigger and catch timeouts, set
the alarm and install a SIGALRM handler as shown in Example 5-28.
Example 5-28. PP4E\System\Processes\signal2.py
"""
set and catch alarm timeout signals in Python; time.sleep doesn't play
well with alarm (or signal in general in my Linux PC), so we call
signal.pause here to do nothing until a signal is received;
"""
import sys, signal, time
def now(): return time.asctime()
def onSignal(signum, stackframe): # python signal handler
print('Got alarm', signum, 'at', now()) # most handlers stay in effect
while True:
print('Setting at', now())
signal.signal(signal.SIGALRM, onSignal) # install signal handler
signal.alarm(5) # do signal in 5 seconds
signal.pause() # wait for signals
Running this script on Cygwin on Windows causes its onSignal handler function to be
invoked every five seconds:
[C:\...\PP4E\System\Processes]$ python signal2.py
Setting at Sun Mar 7 18:37:10 2010
Got alarm 14 at Sun Mar 7 18:37:15 2010
Setting at Sun Mar 7 18:37:15 2010
Got alarm 14 at Sun Mar 7 18:37:20 2010
Setting at Sun Mar 7 18:37:20 2010
Got alarm 14 at Sun Mar 7 18:37:25 2010
Setting at Sun Mar 7 18:37:25 2010
Got alarm 14 at Sun Mar 7 18:37:30 2010
242 | Chapter 5: Parallel System Tools