"""
import sys, signal, time
def now():
return time.asctime()
def onSignal(signum, stackframe): # Python signal handler
print('Got signal', signum, 'at', now()) # most handlers stay in effect
if signum == signal.SIGCHLD: # but sigchld handler is not
print('sigchld caught')
#signal.signal(signal.SIGCHLD, onSignal)
signum = int(sys.argv[1])
signal.signal(signum, onSignal) # install signal handler
while True: signal.pause() # sleep waiting for signals
To run this script, simply put it in the background and send it signals by typing the
kill -signal-number process-id shell command line; this is the shell’s equivalent of
Python’s os.kill function available on Unix-like platforms only. Process IDs are listed
in the PID column of ps command results. Here is this script in action catching signal
numbers 10 (reserved for general use) and 9 (the unavoidable terminate signal):
[...]$ python signal-demo.py 10 &
[1] 10141
[...]$ ps -f
UID PID PPID C STIME TTY TIME CMD
5693094 10141 30778 0 05:00 pts/0 00:00:00 python signal-demo.py 10
5693094 10228 30778 0 05:00 pts/0 00:00:00 ps -f
5693094 30778 30772 0 04:23 pts/0 00:00:00 -bash
[...]$ kill −10 10141
Got signal 10 at Sun Apr 25 05:00:31 2010
[...]$ kill −10 10141
Got signal 10 at Sun Apr 25 05:00:34 2010
[...]$ kill −9 10141
[1]+ Killed python signal-demo.py 10
And in the following the script catches signal 17, which happens to be SIGCHLD on my
Linux server. Signal numbers vary from machine to machine, so you should normally
use their names, not their numbers. SIGCHLD behavior may vary per platform as well.
On my Cygwin install, for example, signal 10 can have different meaning, and signal
20 is SIGCHLD—on Cygwin, the script works as shown on Linux here for signal 10,
but generates an exception if it tries to install on handler for signal 17 (and Cygwin
doesn’t require reaping in any event). See the signal module’s library manual entry for
more details:
[...]$ python signal-demo.py 17 &
[1] 11592
[...]$ ps -f
UID PID PPID C STIME TTY TIME CMD
810 | Chapter 12: Network Scripting