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