Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Signal Handling in Python (http://www.go4expert.com/articles/signal-handling-python-t28332/)

pradeep 4May2012 18:21

Signal Handling in Python
Signals are a limited form of inter-process communication, it analogous to hardware interrupts. It is generally used by the operating system to notify processes about certain issues/states/errors, like division by zero, etc. In case, you want to know read more about signals read Signal and Interrupts.

Python provides a set of functions in the signal which is used to handle signals. To do basic signal handling operations, we'll need to look into the signal.signal() method.

The signal.signal() method needs to arguments, one is the signal number to handle and the second is the function that will be invoked when the signal is received. A working code can explain better than just words, so lets look into a few code samples to under signal handling in Python better.

Simple: Print The Signal Received

In the following code example I'll register handlers for SIGINT and SIGUSR1, which when received, the handler will print the arguments received.

Code: Python


import sys
import signal
import time

def signalHandler(a,b):
    print "Signal received ",a,"==",b;


    print "Wait..."

After executing the program, I'll send a signal to the process and we'll see the output.


[pradeep@deepz-desktop ~]$ /var/www/test/signals.py &
[1] 16391
[pradeep@deepz-desktop ~]$ Wait...

[pradeep@deepz-desktop ~]$ kill -INT 16391
Signal received  2 == <frame object at 0x50687a0>
[pradeep@deepz-desktop ~]$ kill -USR1 16391
Signal received  10 == <frame object at 0x50687a0>

Timing Out A Blocking Operation

At times some functions/operation do not have a way to set a timeout for the operation to complete, as a result the program hangs indefinitely. Here, we'll utilize the SIGALRM to mimic a timeout, see below:

Code: Python

import sys
import signal
import socket

def handler(s, f):
    print 'Signal handler called with signal', s
    raise IOError("Couldn't connect!")

signal.signal(signal.SIGALRM, handler)

## set an alarm to go off after 5 sec, this is our timeout

## the operation that may take a long time/or wait indefinitely, than we expect it to
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.some-non-existant-website.com", 80))

# Disable the alarm, in case the previous operation goes through

saleemamalik 29May2012 12:00

Re: Signal Handling in Python
thank you brother, its really great and use full sharing, i really like it and i find it very use full, keep it up

All times are GMT +5.5. The time now is 05:27.