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