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