Debian Codegraph @

Doc/library/signal.rst

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