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