Go4Expert

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

#!/usr/bin/python

import sys
import signal
import time

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

signal.signal(signal.SIGINT,signalHandler);
signal.signal(signal.SIGUSR1,signalHandler);

while(1):
    print "Wait..."
    time.sleep(10)


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

Code:

[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>
Wait...
[pradeep@deepz-desktop ~]$ kill -USR1 16391
Signal received  10 == <frame object at 0x50687a0>
Wait...


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
signal.alarm(5)

## 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
signal.alarm(0)


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 09:44.