Signal is a registered trademark in the United States and other countries. For media inquiries, contact press@signal.org. The effects of signal in a multithreaded process are unspecified. According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill (2) or raise (3). Integer division by zero has undefined result.
- Usa Signals Vip Insider
- Signalr
- Signal Social Network
- Signal Part 3
- Signal Text App
- Signal App
- Signal The Coral Buddies
This module provides mechanisms to use signal handlers in Python.
General rules¶
The signal.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) and SIGINT
istranslated into a KeyboardInterrupt
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.
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 next bytecode 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.
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 the threading
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
.getsignal()
, pthread_sigmask()
, sigpending()
andsigwait()
functions return human-readableenums
.
The variables defined in the signal
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 for SIGCHLD
is to simply ignore it.
signal.
SIG_IGN
¶This is another standard signal handler, which will simply ignore the givensignal.
signal.
SIGABRT
¶Abort signal from abort(3).
signal.
SIGALRM
¶Timer signal from alarm(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
.
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.
Usa Signals Vip Insider
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.
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 in signal(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 the Ctrl+C keystroke event. This signal canonly be used with os.kill()
.
Availability: Windows.
signal.
CTRL_BREAK_EVENT
¶The signal corresponding to the Ctrl+Break keystroke event. This signal canonly be used with os.kill()
.
Availability: Windows.
New in version 3.2.
signal.
NSIG
¶One more than the number of the highest signal number.
signal.
ITIMER_REAL
¶Decrements interval timer in real time, and delivers SIGALRM
uponexpiration.
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 the how parameter to pthread_sigmask()
indicating that signals are to be blocked.
signal.
SIG_UNBLOCK
¶A possible value for the how parameter to pthread_sigmask()
indicating that signals are to be unblocked.
New in version 3.3.
signal.
SIG_SETMASK
¶A possible value for the how parameter to pthread_sigmask()
indicating that the signal mask is to be replaced.
The signal
module defines one exception:
signal.
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 to setitimer()
.This error is a subtype of OSError
.
New in version 3.3: This error used to be a subtype of IOError
, which is now analias of OSError
.
The signal
module defines the following functions:
signal.
alarm
(time)¶If time is non-zero, this function requests that a SIGALRM
signal besent to the process in time 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. If time 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 page alarm(2) for furtherinformation.
signal.
getsignal
(signalnum)¶Return the current signal handler for the signal signalnum. The returned valuemay be a callable Python object, or one of the special valuessignal.SIG_IGN
, signal.SIG_DFL
or None
. 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, and None
means that the previous signal handler was notinstalled from Python.
signal.
strsignal
(signalnum)¶Return the system description of the signal signalnum, such as“Interrupt”, “Segmentation fault”, etc. Returns None
if the signalis not recognized.
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.
New 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 page signal(2) for furtherinformation.
See also sigwait()
, sigwaitinfo()
, sigtimedwait()
andsigpending()
.
signal.
raise_signal
(signum)¶Sends a signal to the calling process. Returns nothing.
signal.
pidfd_send_signal
(pidfd, sig, siginfo=None, flags=0)¶Send signal sig to the process referred to by file descriptor pidfd.Python does not currently support the siginfo parameter; it must beNone
. The flags argument is provided for future extensions; no flagvalues are currently defined.
See the pidfd_send_signal(2) man page for more information.
Availability: Linux 5.1+
New in version 3.9.
signal.
pthread_kill
(thread_id, signalnum)¶Send the signal signalnum to the thread thread_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 be executed 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 the ident
attribute of threading.Thread
objects to get a suitable valuefor thread_id.
If signalnum 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 an auditing eventsignal.pthread_kill
with arguments thread_id
, signalnum
.
Availability: Unix. See the man page pthread_kill(3) for furtherinformation.
See also os.kill()
.
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 of how, as follows.
SIG_BLOCK
: The set of blocked signals is the union of the currentset and the mask argument.SIG_UNBLOCK
: The signals in mask 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 the maskargument.
mask is a set of signal numbers (e.g. {signal.SIGINT
,signal.SIGTERM
}). Use valid_signals()
for a fullmask including all signals.
For example, signal.pthread_sigmask(signal.SIG_BLOCK,[])
reads thesignal mask of the calling thread.
SIGKILL
and SIGSTOP
cannot be blocked.
Availability: Unix. See the man page sigprocmask(3) andpthread_sigmask(3) for further information.
See also pause()
, sigpending()
and sigwait()
.
New in version 3.3.
signal.
setitimer
(which, seconds, interval=0.0)¶Sets given interval timer (one of signal.ITIMER_REAL
,signal.ITIMER_VIRTUAL
or signal.ITIMER_PROF
) specifiedby which to fire after seconds (float is accepted, different fromalarm()
) and after that every interval seconds (if intervalis non-zero). The interval timer specified by which can be cleared bysetting seconds 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 deliver SIGALRM
,signal.ITIMER_VIRTUAL
sends SIGVTALRM
,and signal.ITIMER_PROF
will deliver SIGPROF
.
The old values are returned as a tuple: (delay, interval).
Attempting to pass an invalid interval timer will cause anItimerError
.
Availability: Unix.
signal.
getitimer
(which)¶Returns current value of a given interval timer specified by which.
Availability: Unix.
signal.
set_wakeup_fd
(fd, *, warn_on_full_buffer=True)¶Set the wakeup file descriptor to fd. When a signal is received, thesignal number is written as a single byte into the fd. This can be used bya library to wakeup a poll or select call, allowing the signal to be fullyprocessed.
The old wakeup fd is returned (or -1 if file descriptor wakeup was notenabled). If fd is -1, file descriptor wakeup is disabled.If not -1, fd must be non-blocking. It is up to the library to removeany bytes from fd before calling poll or select again.
When threads are enabled, this function can only be calledfrom the 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 determine which 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 setwarn_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 fd only 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: if flag is False
, systemcalls will be restarted when interrupted by signal signalnum, otherwisesystem calls will be interrupted. Returns nothing.
Availability: Unix. See the man page siginterrupt(3)for further information.
Note that installing a signal handler with signal()
will reset therestart behaviour to interruptible by implicitly callingsiginterrupt()
with a true flag value for the given signal.
signal.
signal
(signalnum, handler)¶Set the handler for signal signalnum to the function handler. handler canbe a callable Python object taking two arguments (see below), or one of thespecial values signal.SIG_IGN
or signal.SIG_DFL
. The previoussignal handler will be returned (see the description of getsignal()
above). (See the Unix man page signal(2) for further information.)
When threads are enabled, this function can only be calledfrom the main thread of the main interpreter;attempting to call it from other threads will cause a ValueError
exception to be raised.
The handler is called with two arguments: the signal number and the currentstack frame (None
or a frame object; for a description of frame objects,see the description in the type hierarchy or see theattribute descriptions in the inspect
module).
Signalr
On Windows, signal()
can only be called with SIGABRT
,SIGFPE
, SIGILL
, SIGINT
, SIGSEGV
,SIGTERM
, or SIGBREAK
.A ValueError
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 page sigpending(2) for furtherinformation.
See also pause()
, pthread_sigmask()
and sigwait()
.
signal.
sigwait
(sigset)¶Suspend execution of the calling thread until the delivery of one of thesignals specified in the signal set sigset. The function accepts the signal(removes it from the pending list of signals), and returns the signal number.
Availability: Unix. See the man page sigwait(3) for furtherinformation.
See also pause()
, pthread_sigmask()
, sigpending()
,sigwaitinfo()
and sigtimedwait()
.
New in version 3.3.
signal.
sigwaitinfo
(sigset)¶Suspend execution of the calling thread until the delivery of one of thesignals specified in the signal set sigset. The function accepts thesignal and removes it from the pending list of signals. If one of thesignals in sigset 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 anInterruptedError
if it is interrupted by a signal that is not insigset.
The return value is an object representing the data contained in thesiginfo_t
structure, namely: si_signo
, si_code
,si_errno
, si_pid
, si_uid
, si_status
,si_band
.
Availability: Unix. See the man page sigwaitinfo(2) for furtherinformation.
See also pause()
, sigwait()
and sigtimedwait()
.
Changed in version 3.5: The function is now retried if interrupted by a signal not in sigsetand the signal handler does not raise an exception (see PEP 475 forthe rationale).
Signal Social Network
signal.
sigtimedwait
(sigset, timeout)¶Like sigwaitinfo()
, but takes an additional timeout argumentspecifying a timeout. If timeout is specified as 0
, a poll isperformed. Returns None
if a timeout occurs.
Availability: Unix. See the man page sigtimedwait(2) for furtherinformation.
See also pause()
, sigwait()
and sigwaitinfo()
.
Signal Part 3
Changed in version 3.5: The function is now retried with the recomputed timeout if interruptedby a signal not in sigset and the signal handler does not raise anexception (see PEP 475 for the rationale).
Example¶
Signal Text App
Here is a minimal example program. It uses the alarm()
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.
Note on SIGPIPE¶
Signal App
Piping output of your program to tools like head(1) willcause a SIGPIPE
signal to be sent to your process when the receiverof its standard output closes early. This results in an exceptionlike BrokenPipeError:[Errno32]Brokenpipe
. To handle thiscase, wrap your entry point to catch this exception as follows:
Signal The Coral Buddies
Do not set SIGPIPE
’s disposition to SIG_DFL
in order to avoid BrokenPipeError
. Doing that would causeyour program to exit unexpectedly also whenever any socket connectionis interrupted while your program is still writing to it.