signal
— Set handlers for asynchronous events¶
Source code:Lib/signal.py
This module provides mechanisms to use signal handlers in Python.
General rules¶
Thesignal.signal()
function allows defining custom handlers to beexecuted when a signal is received. A small number of default handlers areinstalled:SIGPIPE
is ignored (so write errors on pipes and socketscan be reported as ordinary Python exceptions) andSIGINT
istranslated into aKeyboardInterrupt
exception if the parent processhas not changed it.
A handler for a particular signal, once set, remains installed until it isexplicitly reset (Python emulates the BSD style interface regardless of theunderlying implementation), with the exception of the handler forSIGCHLD
, which follows the underlying implementation.
On WebAssembly platforms, signals are emulated and therefore behavedifferently. Several functions and signals are not available on theseplatforms.
Execution of Python signal handlers¶
A Python signal handler does not get executed inside the low-level (C) signalhandler. Instead, the low-level signal handler sets a flag which tells thevirtual machine to execute the corresponding Python signal handlerat a later point(for example at the nextbytecode instruction).This has consequences:
It makes little sense to catch synchronous errors like
SIGFPE
orSIGSEGV
that are caused by an invalid operation in C code. Pythonwill return from the signal handler to the C code, which is likely to raisethe same signal again, causing Python to apparently hang. From Python 3.3onwards, you can use thefaulthandler
module to report on synchronouserrors.A long-running calculation implemented purely in C (such as regularexpression matching on a large body of text) may run uninterrupted for anarbitrary amount of time, regardless of any signals received. The Pythonsignal handlers will be called when the calculation finishes.
If the handler raises an exception, it will be raised “out of thin air” inthe main thread. See thenote below for adiscussion.
Signals and threads¶
Python signal handlers are always executed in the main Python thread of the main interpreter,even if the signal was received in another thread. This means that signalscan’t be used as a means of inter-thread communication. You can usethe synchronization primitives from thethreading
module instead.
Besides, only the main thread of the main interpreter is allowed to set a new signal handler.
Module contents¶
Changed in version 3.5:signal (SIG*), handler (SIG_DFL
,SIG_IGN
) and sigmask(SIG_BLOCK
,SIG_UNBLOCK
,SIG_SETMASK
)related constants listed below were turned intoenums
(Signals
,Handlers
andSigmasks
respectively).getsignal()
,pthread_sigmask()
,sigpending()
andsigwait()
functions return human-readableenums
asSignals
objects.
The signal module defines three enums:
- classsignal.Signals¶
enum.IntEnum
collection of SIG* constants and the CTRL_* constants.Added in version 3.5.
- classsignal.Handlers¶
enum.IntEnum
collection the constantsSIG_DFL
andSIG_IGN
.Added in version 3.5.
- classsignal.Sigmasks¶
enum.IntEnum
collection the constantsSIG_BLOCK
,SIG_UNBLOCK
andSIG_SETMASK
.Availability: Unix.
See the man pagesigprocmask(2) andpthread_sigmask(3) for further information.
Added in version 3.5.
The variables defined in thesignal
module are:
- signal.SIG_DFL¶
This is one of two standard signal handling options; it will simply performthe default function for the signal. For example, on most systems thedefault action for
SIGQUIT
is to dump core and exit, while thedefault action forSIGCHLD
is to simply ignore it.
- signal.SIG_IGN¶
This is another standard signal handler, which will simply ignore the givensignal.
- signal.SIGALRM¶
Timer signal fromalarm(2).
Availability: Unix.
- signal.SIGBREAK¶
Interrupt from keyboard (CTRL + BREAK).
Availability: Windows.
- signal.SIGBUS¶
Bus error (bad memory access).
Availability: Unix.
- signal.SIGCHLD¶
Child process stopped or terminated.
Availability: Unix.
- signal.SIGCLD¶
Alias to
SIGCHLD
.Availability: not macOS.
- signal.SIGCONT¶
Continue the process if it is currently stopped
Availability: Unix.
- signal.SIGFPE¶
Floating-point exception. For example, division by zero.
See also
ZeroDivisionError
is raised when the second argument of a divisionor modulo operation is zero.
- signal.SIGHUP¶
Hangup detected on controlling terminal or death of controlling process.
Availability: Unix.
- signal.SIGILL¶
Illegal instruction.
- signal.SIGINT¶
Interrupt from keyboard (CTRL + C).
Default action is to raise
KeyboardInterrupt
.
- signal.SIGKILL¶
Kill signal.
It cannot be caught, blocked, or ignored.
Availability: Unix.
- signal.SIGPIPE¶
Broken pipe: write to pipe with no readers.
Default action is to ignore the signal.
Availability: Unix.
- signal.SIGSEGV¶
Segmentation fault: invalid memory reference.
- signal.SIGSTKFLT¶
Stack fault on coprocessor. The Linux kernel does not raise this signal: itcan only be raised in user space.
Availability: Linux.
On architectures where the signal is available. Seethe man pagesignal(7) for further information.
Added in version 3.11.
- signal.SIGTERM¶
Termination signal.
- signal.SIGUSR1¶
User-defined signal 1.
Availability: Unix.
- signal.SIGUSR2¶
User-defined signal 2.
Availability: Unix.
- signal.SIGWINCH¶
Window resize signal.
Availability: Unix.
- SIG*
All the signal numbers are defined symbolically. For example, the hangup signalis defined as
signal.SIGHUP
; the variable names are identical to thenames used in C programs, as found in<signal.h>
. The Unix man page for‘signal()
’ lists the existing signals (on some systems this issignal(2), on others the list is insignal(7)). Note thatnot all systems define the same set of signal names; only those names defined bythe system are defined by this module.
- signal.CTRL_C_EVENT¶
The signal corresponding to theCtrl+C keystroke event. This signal canonly be used with
os.kill()
.Availability: Windows.
Added in version 3.2.
- signal.CTRL_BREAK_EVENT¶
The signal corresponding to theCtrl+Break keystroke event. This signal canonly be used with
os.kill()
.Availability: Windows.
Added in version 3.2.
- signal.NSIG¶
One more than the number of the highest signal number.Use
valid_signals()
to get valid signal numbers.
- signal.ITIMER_VIRTUAL¶
Decrements interval timer only when the process is executing, and deliversSIGVTALRM upon expiration.
- signal.ITIMER_PROF¶
Decrements interval timer both when the process executes and when thesystem is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,this timer is usually used to profile the time spent by the applicationin user and kernel space. SIGPROF is delivered upon expiration.
- signal.SIG_BLOCK¶
A possible value for thehow parameter to
pthread_sigmask()
indicating that signals are to be blocked.Added in version 3.3.
- signal.SIG_UNBLOCK¶
A possible value for thehow parameter to
pthread_sigmask()
indicating that signals are to be unblocked.Added in version 3.3.
- signal.SIG_SETMASK¶
A possible value for thehow parameter to
pthread_sigmask()
indicating that the signal mask is to be replaced.Added in version 3.3.
Thesignal
module defines one exception:
- exceptionsignal.ItimerError¶
Raised to signal an error from the underlying
setitimer()
orgetitimer()
implementation. Expect this error if an invalidinterval timer or a negative time is passed tosetitimer()
.This error is a subtype ofOSError
.
Thesignal
module defines the following functions:
- signal.alarm(time)¶
Iftime is non-zero, this function requests that a
SIGALRM
signal besent to the process intime seconds. Any previously scheduled alarm iscanceled (only one alarm can be scheduled at any time). The returned value isthen the number of seconds before any previously set alarm was to have beendelivered. Iftime is zero, no alarm is scheduled, and any scheduled alarm iscanceled. If the return value is zero, no alarm is currently scheduled.Availability: Unix.
See the man pagealarm(2) for further information.
- signal.getsignal(signalnum)¶
Return the current signal handler for the signalsignalnum. The returned valuemay be a callable Python object, or one of the special values
signal.SIG_IGN
,signal.SIG_DFL
orNone
. Here,signal.SIG_IGN
means that the signal was previously ignored,signal.SIG_DFL
means that the default way of handling the signal waspreviously in use, andNone
means that the previous signal handler was notinstalled from Python.
- signal.strsignal(signalnum)¶
Returns the description of signalsignalnum, such as “Interrupt”for
SIGINT
. ReturnsNone
ifsignalnum has nodescription. RaisesValueError
ifsignalnum is invalid.Added in version 3.8.
- signal.valid_signals()¶
Return the set of valid signal numbers on this platform. This can beless than
range(1,NSIG)
if some signals are reserved by the systemfor internal use.Added in version 3.8.
- signal.pause()¶
Cause the process to sleep until a signal is received; the appropriate handlerwill then be called. Returns nothing.
Availability: Unix.
See the man pagesignal(2) for further information.
See also
sigwait()
,sigwaitinfo()
,sigtimedwait()
andsigpending()
.
- signal.raise_signal(signum)¶
Sends a signal to the calling process. Returns nothing.
Added in version 3.8.
- signal.pidfd_send_signal(pidfd,sig,siginfo=None,flags=0)¶
Send signalsig to the process referred to by file descriptorpidfd.Python does not currently support thesiginfo parameter; it must be
None
. Theflags argument is provided for future extensions; no flagvalues are currently defined.See thepidfd_send_signal(2) man page for more information.
Availability: Linux >= 5.1, Android >=
build-time
API level 31Added in version 3.9.
- signal.pthread_kill(thread_id,signalnum)¶
Send the signalsignalnum to the threadthread_id, another thread in thesame process as the caller. The target thread can be executing any code(Python or not). However, if the target thread is executing the Pythoninterpreter, the Python signal handlers will beexecuted by the mainthread of the main interpreter. Therefore, the only point of sending asignal to a particular Python thread would be to force a running system callto fail with
InterruptedError
.Use
threading.get_ident()
or theident
attribute ofthreading.Thread
objects to get a suitable valueforthread_id.Ifsignalnum is 0, then no signal is sent, but error checking is stillperformed; this can be used to check if the target thread is still running.
Raises anauditing event
signal.pthread_kill
with argumentsthread_id
,signalnum
.Availability: Unix.
See the man pagepthread_kill(3) for further information.
See also
os.kill()
.Added in version 3.3.
- signal.pthread_sigmask(how,mask)¶
Fetch and/or change the signal mask of the calling thread. The signal maskis the set of signals whose delivery is currently blocked for the caller.Return the old signal mask as a set of signals.
The behavior of the call is dependent on the value ofhow, as follows.
SIG_BLOCK
: The set of blocked signals is the union of the currentset and themask argument.SIG_UNBLOCK
: The signals inmask are removed from the currentset of blocked signals. It is permissible to attempt to unblock asignal which is not blocked.SIG_SETMASK
: The set of blocked signals is set to themaskargument.
mask is a set of signal numbers (e.g. {
signal.SIGINT
,signal.SIGTERM
}). Usevalid_signals()
for a fullmask including all signals.For example,
signal.pthread_sigmask(signal.SIG_BLOCK,[])
reads thesignal mask of the calling thread.SIGKILL
andSIGSTOP
cannot be blocked.Availability: Unix.
See the man pagesigprocmask(2) andpthread_sigmask(3) for further information.
See also
pause()
,sigpending()
andsigwait()
.Added in version 3.3.
- signal.setitimer(which,seconds,interval=0.0)¶
Sets given interval timer (one of
signal.ITIMER_REAL
,signal.ITIMER_VIRTUAL
orsignal.ITIMER_PROF
) specifiedbywhich to fire afterseconds (float is accepted, different fromalarm()
) and after that everyinterval seconds (ifintervalis non-zero). The interval timer specified bywhich can be cleared bysettingseconds to zero.When an interval timer fires, a signal is sent to the process.The signal sent is dependent on the timer being used;
signal.ITIMER_REAL
will deliverSIGALRM
,signal.ITIMER_VIRTUAL
sendsSIGVTALRM
,andsignal.ITIMER_PROF
will deliverSIGPROF
.The old values are returned as a tuple: (delay, interval).
Attempting to pass an invalid interval timer will cause an
ItimerError
.Availability: Unix.
- signal.getitimer(which)¶
Returns current value of a given interval timer specified bywhich.
Availability: Unix.
- signal.set_wakeup_fd(fd,*,warn_on_full_buffer=True)¶
Set the wakeup file descriptor tofd. When a signal your program hasregistered a signal handler for is received, the signal number is written asa single byte into the fd. If you haven’t registered a signal handler forthe signals you care about, then nothing will be written to the wakeup fd.This can be used by a library to wakeup a poll or select call, allowing thesignal to be fully processed.
The old wakeup fd is returned (or -1 if file descriptor wakeup was notenabled). Iffd is -1, file descriptor wakeup is disabled.If not -1,fd must be non-blocking. It is up to the library to removeany bytes fromfd before calling poll or select again.
When threads are enabled, this function can only be calledfromthe main thread of the main interpreter;attempting to call it from other threads will cause a
ValueError
exception to be raised.There are two common ways to use this function. In both approaches,you use the fd to wake up when a signal arrives, but then theydiffer in how they determinewhich signal or signals havearrived.
In the first approach, we read the data out of the fd’s buffer, andthe byte values give you the signal numbers. This is simple, but inrare cases it can run into a problem: generally the fd will have alimited amount of buffer space, and if too many signals arrive tooquickly, then the buffer may become full, and some signals may belost. If you use this approach, then you should set
warn_on_full_buffer=True
, which will at least cause a warningto be printed to stderr when signals are lost.In the second approach, we use the wakeup fdonly for wakeups,and ignore the actual byte values. In this case, all we care aboutis whether the fd’s buffer is empty or non-empty; a full bufferdoesn’t indicate a problem at all. If you use this approach, thenyou should set
warn_on_full_buffer=False
, so that your usersare not confused by spurious warning messages.Changed in version 3.5:On Windows, the function now also supports socket handles.
Changed in version 3.7:Added
warn_on_full_buffer
parameter.
- signal.siginterrupt(signalnum,flag)¶
Change system call restart behaviour: ifflag is
False
, systemcalls will be restarted when interrupted by signalsignalnum, otherwisesystem calls will be interrupted. Returns nothing.Availability: Unix.
See the man pagesiginterrupt(3) for further information.
Note that installing a signal handler with
signal()
will reset therestart behaviour to interruptible by implicitly callingsiginterrupt()
with a trueflag value for the given signal.
- signal.signal(signalnum,handler)¶
Set the handler for signalsignalnum to the functionhandler.handler canbe a callable Python object taking two arguments (see below), or one of thespecial values
signal.SIG_IGN
orsignal.SIG_DFL
. The previoussignal handler will be returned (see the description ofgetsignal()
above). (See the Unix man pagesignal(2) for further information.)When threads are enabled, this function can only be calledfromthe main thread of the main interpreter;attempting to call it from other threads will cause a
ValueError
exception to be raised.Thehandler is called with two arguments: the signal number and the currentstack frame (
None
or a frame object; for a description of frame objects,see thedescription in the type hierarchy or see theattribute descriptions in theinspect
module).On Windows,
signal()
can only be called withSIGABRT
,SIGFPE
,SIGILL
,SIGINT
,SIGSEGV
,SIGTERM
, orSIGBREAK
.AValueError
will be raised in any other case.Note that not all systems define the same set of signal names; anAttributeError
will be raised if a signal name is not defined asSIG*
module level constant.
- signal.sigpending()¶
Examine the set of signals that are pending for delivery to the callingthread (i.e., the signals which have been raised while blocked). Return theset of the pending signals.
Availability: Unix.
See the man pagesigpending(2) for further information.
See also
pause()
,pthread_sigmask()
andsigwait()
.Added in version 3.3.
- signal.sigwait(sigset)¶
Suspend execution of the calling thread until the delivery of one of thesignals specified in the signal setsigset. The function accepts the signal(removes it from the pending list of signals), and returns the signal number.
Availability: Unix.
See the man pagesigwait(3) for further information.
See also
pause()
,pthread_sigmask()
,sigpending()
,sigwaitinfo()
andsigtimedwait()
.Added in version 3.3.
- signal.sigwaitinfo(sigset)¶
Suspend execution of the calling thread until the delivery of one of thesignals specified in the signal setsigset. The function accepts thesignal and removes it from the pending list of signals. If one of thesignals insigset is already pending for the calling thread, the functionwill return immediately with information about that signal. The signalhandler is not called for the delivered signal. The function raises an
InterruptedError
if it is interrupted by a signal that is not insigset.The return value is an object representing the data contained in the
siginfo_t
structure, namely:si_signo
,si_code
,si_errno
,si_pid
,si_uid
,si_status
,si_band
.Availability: Unix.
See the man pagesigwaitinfo(2) for further information.
See also
pause()
,sigwait()
andsigtimedwait()
.Added in version 3.3.
Changed in version 3.5:The function is now retried if interrupted by a signal not insigsetand the signal handler does not raise an exception (seePEP 475 forthe rationale).
- signal.sigtimedwait(sigset,timeout)¶
Like
sigwaitinfo()
, but takes an additionaltimeout argumentspecifying a timeout. Iftimeout is specified as0
, a poll isperformed. ReturnsNone
if a timeout occurs.Availability: Unix.
See the man pagesigtimedwait(2) for further information.
See also
pause()
,sigwait()
andsigwaitinfo()
.Added in version 3.3.
Changed in version 3.5:The function is now retried with the recomputedtimeout if interruptedby a signal not insigset and the signal handler does not raise anexception (seePEP 475 for the rationale).
Examples¶
Here is a minimal example program. It uses thealarm()
function to limitthe time spent waiting to open a file; this is useful if the file is for aserial device that may not be turned on, which would normally cause theos.open()
to hang indefinitely. The solution is to set a 5-second alarmbefore opening the file; if the operation takes too long, the alarm signal willbe sent, and the handler raises an exception.
importsignal,osdefhandler(signum,frame):signame=signal.Signals(signum).nameprint(f'Signal handler called with signal{signame} ({signum})')raiseOSError("Couldn't open device!")# Set the signal handler and a 5-second alarmsignal.signal(signal.SIGALRM,handler)signal.alarm(5)# This open() may hang indefinitelyfd=os.open('/dev/ttyS0',os.O_RDWR)signal.alarm(0)# Disable the alarm
Note on SIGPIPE¶
Piping output of your program to tools likehead(1) willcause aSIGPIPE
signal to be sent to your process when the receiverof its standard output closes early. This results in an exceptionlikeBrokenPipeError:[Errno32]Brokenpipe
. To handle thiscase, wrap your entry point to catch this exception as follows:
importosimportsysdefmain():try:# simulate large output (your code replaces this loop)forxinrange(10000):print("y")# flush output here to force SIGPIPE to be triggered# while inside this try block.sys.stdout.flush()exceptBrokenPipeError:# Python flushes standard streams on exit; redirect remaining output# to devnull to avoid another BrokenPipeError at shutdowndevnull=os.open(os.devnull,os.O_WRONLY)os.dup2(devnull,sys.stdout.fileno())sys.exit(1)# Python exits with error code 1 on EPIPEif__name__=='__main__':main()
Do not setSIGPIPE
’s disposition toSIG_DFL
inorder to avoidBrokenPipeError
. Doing that would causeyour program to exit unexpectedly whenever any socketconnection is interrupted while your program is still writing toit.
Note on Signal Handlers and Exceptions¶
If a signal handler raises an exception, the exception will be propagated tothe main thread and may be raised after anybytecode instruction. Mostnotably, aKeyboardInterrupt
may appear at any point during execution.Most Python code, including the standard library, cannot be made robust againstthis, and so aKeyboardInterrupt
(or any other exception resulting froma signal handler) may on rare occasions put the program in an unexpected state.
To illustrate this issue, consider the following code:
classSpamContext:def__init__(self):self.lock=threading.Lock()def__enter__(self):# If KeyboardInterrupt occurs here, everything is fineself.lock.acquire()# If KeyboardInterrupt occurs here, __exit__ will not be called...# KeyboardInterrupt could occur just before the function returnsdef__exit__(self,exc_type,exc_val,exc_tb):...self.lock.release()
For many programs, especially those that merely want to exit onKeyboardInterrupt
, this is not a problem, but applications that arecomplex or require high reliability should avoid raising exceptions from signalhandlers. They should also avoid catchingKeyboardInterrupt
as a meansof gracefully shutting down. Instead, they should install their ownSIGINT
handler. Below is an example of an HTTP server that avoidsKeyboardInterrupt
:
importsignalimportsocketfromselectorsimportDefaultSelector,EVENT_READfromhttp.serverimportHTTPServer,SimpleHTTPRequestHandlerinterrupt_read,interrupt_write=socket.socketpair()defhandler(signum,frame):print('Signal handler called with signal',signum)interrupt_write.send(b'\0')signal.signal(signal.SIGINT,handler)defserve_forever(httpd):sel=DefaultSelector()sel.register(interrupt_read,EVENT_READ)sel.register(httpd,EVENT_READ)whileTrue:forkey,_insel.select():ifkey.fileobj==interrupt_read:interrupt_read.recv(1)returnifkey.fileobj==httpd:httpd.handle_request()print("Serving on port 8000")httpd=HTTPServer(('',8000),SimpleHTTPRequestHandler)serve_forever(httpd)print("Shutdown...")