1:mod:`signal` --- Set handlers for asynchronous events
2======================================================
3
4.. module:: signal
5   :synopsis: Set handlers for asynchronous events.
6
7--------------
8
9This module provides mechanisms to use signal handlers in Python.
10
11
12General rules
13-------------
14
15The :func:`signal.signal` function allows defining custom handlers to be
16executed when a signal is received.  A small number of default handlers are
17installed: :const:`SIGPIPE` is ignored (so write errors on pipes and sockets
18can be reported as ordinary Python exceptions) and :const:`SIGINT` is
19translated into a :exc:`KeyboardInterrupt` exception if the parent process
20has not changed it.
21
22A handler for a particular signal, once set, remains installed until it is
23explicitly reset (Python emulates the BSD style interface regardless of the
24underlying implementation), with the exception of the handler for
25:const:`SIGCHLD`, which follows the underlying implementation.
26
27
28Execution of Python signal handlers
29^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30
31A Python signal handler does not get executed inside the low-level (C) signal
32handler.  Instead, the low-level signal handler sets a flag which tells the
33:term:`virtual machine` to execute the corresponding Python signal handler
34at a later point(for example at the next :term:`bytecode` instruction).
35This has consequences:
36
37* It makes little sense to catch synchronous errors like :const:`SIGFPE` or
38  :const:`SIGSEGV` that are caused by an invalid operation in C code.  Python
39  will return from the signal handler to the C code, which is likely to raise
40  the same signal again, causing Python to apparently hang.  From Python 3.3
41  onwards, you can use the :mod:`faulthandler` module to report on synchronous
42  errors.
43
44* A long-running calculation implemented purely in C (such as regular
45  expression matching on a large body of text) may run uninterrupted for an
46  arbitrary amount of time, regardless of any signals received.  The Python
47  signal handlers will be called when the calculation finishes.
48
49
50.. _signals-and-threads:
51
52
53Signals and threads
54^^^^^^^^^^^^^^^^^^^
55
56Python signal handlers are always executed in the main Python thread,
57even if the signal was received in another thread.  This means that signals
58can't be used as a means of inter-thread communication.  You can use
59the synchronization primitives from the :mod:`threading` module instead.
60
61Besides, only the main thread is allowed to set a new signal handler.
62
63
64Module contents
65---------------
66
67.. versionchanged:: 3.5
68   signal (SIG*), handler (:const:`SIG_DFL`, :const:`SIG_IGN`) and sigmask
69   (:const:`SIG_BLOCK`, :const:`SIG_UNBLOCK`, :const:`SIG_SETMASK`)
70   related constants listed below were turned into
71   :class:`enums <enum.IntEnum>`.
72   :func:`getsignal`, :func:`pthread_sigmask`, :func:`sigpending` and
73   :func:`sigwait` functions return human-readable
74   :class:`enums <enum.IntEnum>`.
75
76
77The variables defined in the :mod:`signal` module are:
78
79
80.. data:: SIG_DFL
81
82   This is one of two standard signal handling options; it will simply perform
83   the default function for the signal.  For example, on most systems the
84   default action for :const:`SIGQUIT` is to dump core and exit, while the
85   default action for :const:`SIGCHLD` is to simply ignore it.
86
87
88.. data:: SIG_IGN
89
90   This is another standard signal handler, which will simply ignore the given
91   signal.
92
93
94.. data:: SIGABRT
95
96   Abort signal from :manpage:`abort(3)`.
97
98.. data:: SIGALRM
99
100   Timer signal from :manpage:`alarm(2)`.
101
102   .. availability:: Unix.
103
104.. data:: SIGBREAK
105
106   Interrupt from keyboard (CTRL + BREAK).
107
108   .. availability:: Windows.
109
110.. data:: SIGBUS
111
112   Bus error (bad memory access).
113
114   .. availability:: Unix.
115
116.. data:: SIGCHLD
117
118   Child process stopped or terminated.
119
120   .. availability:: Unix.
121
122.. data:: SIGCLD
123
124   Alias to :data:`SIGCHLD`.
125
126.. data:: SIGCONT
127
128   Continue the process if it is currently stopped
129
130   .. availability:: Unix.
131
132.. data:: SIGFPE
133
134   Floating-point exception. For example, division by zero.
135
136   .. seealso::
137      :exc:`ZeroDivisionError` is raised when the second argument of a division
138      or modulo operation is zero.
139
140.. data:: SIGHUP
141
142   Hangup detected on controlling terminal or death of controlling process.
143
144   .. availability:: Unix.
145
146.. data:: SIGILL
147
148   Illegal instruction.
149
150.. data:: SIGINT
151
152   Interrupt from keyboard (CTRL + C).
153
154   Default action is to raise :exc:`KeyboardInterrupt`.
155
156.. data:: SIGKILL
157
158   Kill signal.
159
160   It cannot be caught, blocked, or ignored.
161
162   .. availability:: Unix.
163
164.. data:: SIGPIPE
165
166   Broken pipe: write to pipe with no readers.
167
168   Default action is to ignore the signal.
169
170   .. availability:: Unix.
171
172.. data:: SIGSEGV
173
174   Segmentation fault: invalid memory reference.
175
176.. data:: SIGTERM
177
178   Termination signal.
179
180.. data:: SIGUSR1
181
182   User-defined signal 1.
183
184   .. availability:: Unix.
185
186.. data:: SIGUSR2
187
188   User-defined signal 2.
189
190   .. availability:: Unix.
191
192.. data:: SIGWINCH
193
194   Window resize signal.
195
196   .. availability:: Unix.
197
198.. data:: SIG*
199
200   All the signal numbers are defined symbolically.  For example, the hangup signal
201   is defined as :const:`signal.SIGHUP`; the variable names are identical to the
202   names used in C programs, as found in ``<signal.h>``.  The Unix man page for
203   ':c:func:`signal`' lists the existing signals (on some systems this is
204   :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
205   not all systems define the same set of signal names; only those names defined by
206   the system are defined by this module.
207
208
209.. data:: CTRL_C_EVENT
210
211   The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can
212   only be used with :func:`os.kill`.
213
214   .. availability:: Windows.
215
216   .. versionadded:: 3.2
217
218
219.. data:: CTRL_BREAK_EVENT
220
221   The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can
222   only be used with :func:`os.kill`.
223
224   .. availability:: Windows.
225
226   .. versionadded:: 3.2
227
228
229.. data:: NSIG
230
231   One more than the number of the highest signal number.
232
233
234.. data:: ITIMER_REAL
235
236   Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
237   expiration.
238
239
240.. data:: ITIMER_VIRTUAL
241
242   Decrements interval timer only when the process is executing, and delivers
243   SIGVTALRM upon expiration.
244
245
246.. data:: ITIMER_PROF
247
248   Decrements interval timer both when the process executes and when the
249   system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
250   this timer is usually used to profile the time spent by the application
251   in user and kernel space. SIGPROF is delivered upon expiration.
252
253
254.. data:: SIG_BLOCK
255
256   A possible value for the *how* parameter to :func:`pthread_sigmask`
257   indicating that signals are to be blocked.
258
259   .. versionadded:: 3.3
260
261.. data:: SIG_UNBLOCK
262
263   A possible value for the *how* parameter to :func:`pthread_sigmask`
264   indicating that signals are to be unblocked.
265
266   .. versionadded:: 3.3
267
268.. data:: SIG_SETMASK
269
270   A possible value for the *how* parameter to :func:`pthread_sigmask`
271   indicating that the signal mask is to be replaced.
272
273   .. versionadded:: 3.3
274
275
276The :mod:`signal` module defines one exception:
277
278.. exception:: ItimerError
279
280   Raised to signal an error from the underlying :func:`setitimer` or
281   :func:`getitimer` implementation. Expect this error if an invalid
282   interval timer or a negative time is passed to :func:`setitimer`.
283   This error is a subtype of :exc:`OSError`.
284
285   .. versionadded:: 3.3
286      This error used to be a subtype of :exc:`IOError`, which is now an
287      alias of :exc:`OSError`.
288
289
290The :mod:`signal` module defines the following functions:
291
292
293.. function:: alarm(time)
294
295   If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
296   sent to the process in *time* seconds. Any previously scheduled alarm is
297   canceled (only one alarm can be scheduled at any time).  The returned value is
298   then the number of seconds before any previously set alarm was to have been
299   delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
300   canceled.  If the return value is zero, no alarm is currently scheduled.
301
302   .. availability:: Unix.  See the man page :manpage:`alarm(2)` for further
303      information.
304
305
306.. function:: getsignal(signalnum)
307
308   Return the current signal handler for the signal *signalnum*. The returned value
309   may be a callable Python object, or one of the special values
310   :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`.  Here,
311   :const:`signal.SIG_IGN` means that the signal was previously ignored,
312   :const:`signal.SIG_DFL` means that the default way of handling the signal was
313   previously in use, and ``None`` means that the previous signal handler was not
314   installed from Python.
315
316
317.. function:: strsignal(signalnum)
318
319   Return the system description of the signal *signalnum*, such as
320   "Interrupt", "Segmentation fault", etc. Returns :const:`None` if the signal
321   is not recognized.
322
323   .. versionadded:: 3.8
324
325
326.. function:: valid_signals()
327
328   Return the set of valid signal numbers on this platform.  This can be
329   less than ``range(1, NSIG)`` if some signals are reserved by the system
330   for internal use.
331
332   .. versionadded:: 3.8
333
334
335.. function:: pause()
336
337   Cause the process to sleep until a signal is received; the appropriate handler
338   will then be called.  Returns nothing.
339
340   .. availability:: Unix.  See the man page :manpage:`signal(2)` for further
341      information.
342
343   See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and
344   :func:`sigpending`.
345
346
347.. function:: raise_signal(signum)
348
349   Sends a signal to the calling process. Returns nothing.
350
351   .. versionadded:: 3.8
352
353
354.. function:: pthread_kill(thread_id, signalnum)
355
356   Send the signal *signalnum* to the thread *thread_id*, another thread in the
357   same process as the caller.  The target thread can be executing any code
358   (Python or not).  However, if the target thread is executing the Python
359   interpreter, the Python signal handlers will be :ref:`executed by the main
360   thread <signals-and-threads>`.  Therefore, the only point of sending a
361   signal to a particular Python thread would be to force a running system call
362   to fail with :exc:`InterruptedError`.
363
364   Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
365   attribute of :class:`threading.Thread` objects to get a suitable value
366   for *thread_id*.
367
368   If *signalnum* is 0, then no signal is sent, but error checking is still
369   performed; this can be used to check if the target thread is still running.
370
371   .. audit-event:: signal.pthread_kill thread_id,signalnum signal.pthread_kill
372
373   .. availability:: Unix.  See the man page :manpage:`pthread_kill(3)` for further
374      information.
375
376   See also :func:`os.kill`.
377
378   .. versionadded:: 3.3
379
380
381.. function:: pthread_sigmask(how, mask)
382
383   Fetch and/or change the signal mask of the calling thread.  The signal mask
384   is the set of signals whose delivery is currently blocked for the caller.
385   Return the old signal mask as a set of signals.
386
387   The behavior of the call is dependent on the value of *how*, as follows.
388
389   * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
390     set and the *mask* argument.
391   * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
392     set of blocked signals.  It is permissible to attempt to unblock a
393     signal which is not blocked.
394   * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
395     argument.
396
397   *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
398   :const:`signal.SIGTERM`}). Use :func:`~signal.valid_signals` for a full
399   mask including all signals.
400
401   For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
402   signal mask of the calling thread.
403
404   :data:`SIGKILL` and :data:`SIGSTOP` cannot be blocked.
405
406   .. availability:: Unix.  See the man page :manpage:`sigprocmask(3)` and
407      :manpage:`pthread_sigmask(3)` for further information.
408
409   See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
410
411   .. versionadded:: 3.3
412
413
414.. function:: setitimer(which, seconds, interval=0.0)
415
416   Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
417   :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
418   by *which* to fire after *seconds* (float is accepted, different from
419   :func:`alarm`) and after that every *interval* seconds (if *interval*
420   is non-zero). The interval timer specified by *which* can be cleared by
421   setting *seconds* to zero.
422
423   When an interval timer fires, a signal is sent to the process.
424   The signal sent is dependent on the timer being used;
425   :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
426   :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
427   and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
428
429   The old values are returned as a tuple: (delay, interval).
430
431   Attempting to pass an invalid interval timer will cause an
432   :exc:`ItimerError`.
433
434   .. availability:: Unix.
435
436
437.. function:: getitimer(which)
438
439   Returns current value of a given interval timer specified by *which*.
440
441   .. availability:: Unix.
442
443
444.. function:: set_wakeup_fd(fd, *, warn_on_full_buffer=True)
445
446   Set the wakeup file descriptor to *fd*.  When a signal is received, the
447   signal number is written as a single byte into the fd.  This can be used by
448   a library to wakeup a poll or select call, allowing the signal to be fully
449   processed.
450
451   The old wakeup fd is returned (or -1 if file descriptor wakeup was not
452   enabled).  If *fd* is -1, file descriptor wakeup is disabled.
453   If not -1, *fd* must be non-blocking.  It is up to the library to remove
454   any bytes from *fd* before calling poll or select again.
455
456   When threads are enabled, this function can only be called from the main thread;
457   attempting to call it from other threads will cause a :exc:`ValueError`
458   exception to be raised.
459
460   There are two common ways to use this function. In both approaches,
461   you use the fd to wake up when a signal arrives, but then they
462   differ in how they determine *which* signal or signals have
463   arrived.
464
465   In the first approach, we read the data out of the fd's buffer, and
466   the byte values give you the signal numbers. This is simple, but in
467   rare cases it can run into a problem: generally the fd will have a
468   limited amount of buffer space, and if too many signals arrive too
469   quickly, then the buffer may become full, and some signals may be
470   lost. If you use this approach, then you should set
471   ``warn_on_full_buffer=True``, which will at least cause a warning
472   to be printed to stderr when signals are lost.
473
474   In the second approach, we use the wakeup fd *only* for wakeups,
475   and ignore the actual byte values. In this case, all we care about
476   is whether the fd's buffer is empty or non-empty; a full buffer
477   doesn't indicate a problem at all. If you use this approach, then
478   you should set ``warn_on_full_buffer=False``, so that your users
479   are not confused by spurious warning messages.
480
481   .. versionchanged:: 3.5
482      On Windows, the function now also supports socket handles.
483
484   .. versionchanged:: 3.7
485      Added ``warn_on_full_buffer`` parameter.
486
487.. function:: siginterrupt(signalnum, flag)
488
489   Change system call restart behaviour: if *flag* is :const:`False`, system
490   calls will be restarted when interrupted by signal *signalnum*, otherwise
491   system calls will be interrupted.  Returns nothing.
492
493   .. availability:: Unix.  See the man page :manpage:`siginterrupt(3)`
494      for further information.
495
496   Note that installing a signal handler with :func:`signal` will reset the
497   restart behaviour to interruptible by implicitly calling
498   :c:func:`siginterrupt` with a true *flag* value for the given signal.
499
500
501.. function:: signal(signalnum, handler)
502
503   Set the handler for signal *signalnum* to the function *handler*.  *handler* can
504   be a callable Python object taking two arguments (see below), or one of the
505   special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`.  The previous
506   signal handler will be returned (see the description of :func:`getsignal`
507   above).  (See the Unix man page :manpage:`signal(2)` for further information.)
508
509   When threads are enabled, this function can only be called from the main thread;
510   attempting to call it from other threads will cause a :exc:`ValueError`
511   exception to be raised.
512
513   The *handler* is called with two arguments: the signal number and the current
514   stack frame (``None`` or a frame object; for a description of frame objects,
515   see the :ref:`description in the type hierarchy <frame-objects>` or see the
516   attribute descriptions in the :mod:`inspect` module).
517
518   On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
519   :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`,
520   :const:`SIGTERM`, or :const:`SIGBREAK`.
521   A :exc:`ValueError` will be raised in any other case.
522   Note that not all systems define the same set of signal names; an
523   :exc:`AttributeError` will be raised if a signal name is not defined as
524   ``SIG*`` module level constant.
525
526
527.. function:: sigpending()
528
529   Examine the set of signals that are pending for delivery to the calling
530   thread (i.e., the signals which have been raised while blocked).  Return the
531   set of the pending signals.
532
533   .. availability:: Unix.  See the man page :manpage:`sigpending(2)` for further
534      information.
535
536   See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
537
538   .. versionadded:: 3.3
539
540
541.. function:: sigwait(sigset)
542
543   Suspend execution of the calling thread until the delivery of one of the
544   signals specified in the signal set *sigset*.  The function accepts the signal
545   (removes it from the pending list of signals), and returns the signal number.
546
547   .. availability:: Unix.  See the man page :manpage:`sigwait(3)` for further
548      information.
549
550   See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`,
551   :func:`sigwaitinfo` and :func:`sigtimedwait`.
552
553   .. versionadded:: 3.3
554
555
556.. function:: sigwaitinfo(sigset)
557
558   Suspend execution of the calling thread until the delivery of one of the
559   signals specified in the signal set *sigset*.  The function accepts the
560   signal and removes it from the pending list of signals. If one of the
561   signals in *sigset* is already pending for the calling thread, the function
562   will return immediately with information about that signal. The signal
563   handler is not called for the delivered signal. The function raises an
564   :exc:`InterruptedError` if it is interrupted by a signal that is not in
565   *sigset*.
566
567   The return value is an object representing the data contained in the
568   :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`,
569   :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`,
570   :attr:`si_band`.
571
572   .. availability:: Unix.  See the man page :manpage:`sigwaitinfo(2)` for further
573      information.
574
575   See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`.
576
577   .. versionadded:: 3.3
578
579   .. versionchanged:: 3.5
580      The function is now retried if interrupted by a signal not in *sigset*
581      and the signal handler does not raise an exception (see :pep:`475` for
582      the rationale).
583
584
585.. function:: sigtimedwait(sigset, timeout)
586
587   Like :func:`sigwaitinfo`, but takes an additional *timeout* argument
588   specifying a timeout. If *timeout* is specified as :const:`0`, a poll is
589   performed. Returns :const:`None` if a timeout occurs.
590
591   .. availability:: Unix.  See the man page :manpage:`sigtimedwait(2)` for further
592      information.
593
594   See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`.
595
596   .. versionadded:: 3.3
597
598   .. versionchanged:: 3.5
599      The function is now retried with the recomputed *timeout* if interrupted
600      by a signal not in *sigset* and the signal handler does not raise an
601      exception (see :pep:`475` for the rationale).
602
603
604.. _signal-example:
605
606Example
607-------
608
609Here is a minimal example program. It uses the :func:`alarm` function to limit
610the time spent waiting to open a file; this is useful if the file is for a
611serial device that may not be turned on, which would normally cause the
612:func:`os.open` to hang indefinitely.  The solution is to set a 5-second alarm
613before opening the file; if the operation takes too long, the alarm signal will
614be sent, and the handler raises an exception. ::
615
616   import signal, os
617
618   def handler(signum, frame):
619       print('Signal handler called with signal', signum)
620       raise OSError("Couldn't open device!")
621
622   # Set the signal handler and a 5-second alarm
623   signal.signal(signal.SIGALRM, handler)
624   signal.alarm(5)
625
626   # This open() may hang indefinitely
627   fd = os.open('/dev/ttyS0', os.O_RDWR)
628
629   signal.alarm(0)          # Disable the alarm
630
631Note on SIGPIPE
632---------------
633
634Piping output of your program to tools like :manpage:`head(1)` will
635cause a :const:`SIGPIPE` signal to be sent to your process when the receiver
636of its standard output closes early.  This results in an exception
637like :code:`BrokenPipeError: [Errno 32] Broken pipe`.  To handle this
638case, wrap your entry point to catch this exception as follows::
639
640    import os
641    import sys
642
643    def main():
644        try:
645            # simulate large output (your code replaces this loop)
646            for x in range(10000):
647                print("y")
648            # flush output here to force SIGPIPE to be triggered
649            # while inside this try block.
650            sys.stdout.flush()
651        except BrokenPipeError:
652            # Python flushes standard streams on exit; redirect remaining output
653            # to devnull to avoid another BrokenPipeError at shutdown
654            devnull = os.open(os.devnull, os.O_WRONLY)
655            os.dup2(devnull, sys.stdout.fileno())
656            sys.exit(1)  # Python exits with error code 1 on EPIPE
657
658    if __name__ == '__main__':
659        main()
660
661Do not set :const:`SIGPIPE`'s disposition to :const:`SIG_DFL`
662in order to avoid :exc:`BrokenPipeError`.  Doing that would cause
663your program to exit unexpectedly also whenever any socket connection
664is interrupted while your program is still writing to it.
665