Come catturare un segnale Unix con Python

Unix Signals, to be short, are various notifications sent to a process in order to notify it of various “important” events. By their nature, they interrupt whatever the process is doing at this minute, and force it to handle them immediately. Each signal has an integer number that represents it (1, 2 and so on), as well as a symbolic name that is usually defined in the file /usr/include/signal.h

[via | Introduction to Unix Signal Programming]

Un modo molto semplice per catturare un segnale asincrono in un sistema Unix con Python è il seguente:

Signal Traps

#! /usr/local/bin/python

import signal import sys

def signal_handler(signal, frame):
        print 'You pressed Ctrl+C!'
        sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C'
while 1:
        continue

signal.SIGINT indica la costante che identifica il segnale, in questo caso il segnale di Interrupt del processo (mandato, per capirci, quando interrompiamo un processo con ctrl+c da shell). Ad esso possiamo sostituire un’altra costante identificativa. Per una lista dei segnali disponibili è possibile consultare la pagina del manuale di Unix:

man signal (7)

All’arrivo del segnale l’handler chiama il metodo signal_handler, il quale in questo caso stampa una stringa ed esce, ma in casi più realistici può effettuare operazioni di freezing del contesto o chiusura e aggiornamento di file o strutture dati. Per ulteriori informazioni sulla gestione dei segnali ci possiamo rifare all’ottima documentazione di Python.

Tags: ,

Leave a Reply