blob: 8b3ab412bd368f2f5a544fa0fd9135a25beed0b3 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`signal` --- Set handlers for asynchronous events
2======================================================
3
4.. module:: signal
5 :synopsis: Set handlers for asynchronous events.
6
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007--------------
Georg Brandl116aa622007-08-15 14:28:22 +00008
Antoine Pitrou6afd11c2012-03-31 20:56:21 +02009This module provides mechanisms to use signal handlers in Python.
Georg Brandl116aa622007-08-15 14:28:22 +000010
Georg Brandl116aa622007-08-15 14:28:22 +000011
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020012General rules
13-------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Martin Panterc04fb562016-02-10 05:44:01 +000015The :func:`signal.signal` function allows defining custom handlers to be
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020016executed when a signal is received. A small number of default handlers are
17installed: :const:`SIGPIPE` is ignored (so write errors on pipes and sockets
18can be reported as ordinary Python exceptions) and :const:`SIGINT` is
Julien Palarde85ef7a2019-05-07 17:27:48 +020019translated into a :exc:`KeyboardInterrupt` exception if the parent process
20has not changed it.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020022A handler for a particular signal, once set, remains installed until it is
23explicitly reset (Python emulates the BSD style interface regardless of the
24underlying implementation), with the exception of the handler for
25:const:`SIGCHLD`, which follows the underlying implementation.
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandl116aa622007-08-15 14:28:22 +000027
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020028Execution of Python signal handlers
29^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30
31A Python signal handler does not get executed inside the low-level (C) signal
32handler. Instead, the low-level signal handler sets a flag which tells the
33:term:`virtual machine` to execute the corresponding Python signal handler
34at a later point(for example at the next :term:`bytecode` instruction).
35This has consequences:
36
37* It makes little sense to catch synchronous errors like :const:`SIGFPE` or
Georg Brandlc377fe22013-10-06 21:22:42 +020038 :const:`SIGSEGV` that are caused by an invalid operation in C code. Python
39 will return from the signal handler to the C code, which is likely to raise
40 the same signal again, causing Python to apparently hang. From Python 3.3
41 onwards, you can use the :mod:`faulthandler` module to report on synchronous
42 errors.
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020043
44* A long-running calculation implemented purely in C (such as regular
45 expression matching on a large body of text) may run uninterrupted for an
46 arbitrary amount of time, regardless of any signals received. The Python
47 signal handlers will be called when the calculation finishes.
48
49
Antoine Pitrou682d4432012-03-31 21:09:00 +020050.. _signals-and-threads:
51
52
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020053Signals and threads
54^^^^^^^^^^^^^^^^^^^
55
56Python signal handlers are always executed in the main Python thread,
57even if the signal was received in another thread. This means that signals
58can't be used as a means of inter-thread communication. You can use
59the synchronization primitives from the :mod:`threading` module instead.
60
61Besides, only the main thread is allowed to set a new signal handler.
62
63
64Module contents
65---------------
Georg Brandl116aa622007-08-15 14:28:22 +000066
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020067.. versionchanged:: 3.5
68 signal (SIG*), handler (:const:`SIG_DFL`, :const:`SIG_IGN`) and sigmask
69 (:const:`SIG_BLOCK`, :const:`SIG_UNBLOCK`, :const:`SIG_SETMASK`)
70 related constants listed below were turned into
71 :class:`enums <enum.IntEnum>`.
72 :func:`getsignal`, :func:`pthread_sigmask`, :func:`sigpending` and
73 :func:`sigwait` functions return human-readable
74 :class:`enums <enum.IntEnum>`.
75
76
Georg Brandl116aa622007-08-15 14:28:22 +000077The variables defined in the :mod:`signal` module are:
78
79
80.. data:: SIG_DFL
81
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000082 This is one of two standard signal handling options; it will simply perform
83 the default function for the signal. For example, on most systems the
84 default action for :const:`SIGQUIT` is to dump core and exit, while the
85 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000086
87
88.. data:: SIG_IGN
89
90 This is another standard signal handler, which will simply ignore the given
91 signal.
92
93
94.. data:: SIG*
95
96 All the signal numbers are defined symbolically. For example, the hangup signal
97 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
Géry Ogamcfebfef2019-08-06 23:12:22 +020098 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Georg Brandl60203b42010-10-06 10:11:56 +000099 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +0000100 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
101 not all systems define the same set of signal names; only those names defined by
102 the system are defined by this module.
103
104
Brian Curtineb24d742010-04-12 17:16:38 +0000105.. data:: CTRL_C_EVENT
106
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300107 The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000108 only be used with :func:`os.kill`.
109
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400110 .. availability:: Windows.
Brian Curtineb24d742010-04-12 17:16:38 +0000111
Brian Curtin904bd392010-04-20 15:28:06 +0000112 .. versionadded:: 3.2
113
Brian Curtineb24d742010-04-12 17:16:38 +0000114
115.. data:: CTRL_BREAK_EVENT
116
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300117 The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000118 only be used with :func:`os.kill`.
119
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400120 .. availability:: Windows.
Brian Curtineb24d742010-04-12 17:16:38 +0000121
Brian Curtin904bd392010-04-20 15:28:06 +0000122 .. versionadded:: 3.2
123
Brian Curtineb24d742010-04-12 17:16:38 +0000124
Georg Brandl116aa622007-08-15 14:28:22 +0000125.. data:: NSIG
126
127 One more than the number of the highest signal number.
128
Martin v. Löwis823725e2008-03-24 13:39:54 +0000129
Georg Brandl48310cd2009-01-03 21:18:54 +0000130.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000131
Georg Brandl18244152009-09-02 20:34:52 +0000132 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
133 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000134
135
Georg Brandl48310cd2009-01-03 21:18:54 +0000136.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000137
Georg Brandl48310cd2009-01-03 21:18:54 +0000138 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000139 SIGVTALRM upon expiration.
140
141
142.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000143
144 Decrements interval timer both when the process executes and when the
145 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
146 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000147 in user and kernel space. SIGPROF is delivered upon expiration.
148
149
Victor Stinnera9293352011-04-30 15:21:58 +0200150.. data:: SIG_BLOCK
151
152 A possible value for the *how* parameter to :func:`pthread_sigmask`
153 indicating that signals are to be blocked.
154
155 .. versionadded:: 3.3
156
157.. data:: SIG_UNBLOCK
158
159 A possible value for the *how* parameter to :func:`pthread_sigmask`
160 indicating that signals are to be unblocked.
161
162 .. versionadded:: 3.3
163
164.. data:: SIG_SETMASK
165
166 A possible value for the *how* parameter to :func:`pthread_sigmask`
167 indicating that the signal mask is to be replaced.
168
169 .. versionadded:: 3.3
170
171
Martin v. Löwis823725e2008-03-24 13:39:54 +0000172The :mod:`signal` module defines one exception:
173
174.. exception:: ItimerError
175
176 Raised to signal an error from the underlying :func:`setitimer` or
177 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000178 interval timer or a negative time is passed to :func:`setitimer`.
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200179 This error is a subtype of :exc:`OSError`.
180
181 .. versionadded:: 3.3
182 This error used to be a subtype of :exc:`IOError`, which is now an
183 alias of :exc:`OSError`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000184
185
Georg Brandl116aa622007-08-15 14:28:22 +0000186The :mod:`signal` module defines the following functions:
187
188
189.. function:: alarm(time)
190
191 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
192 sent to the process in *time* seconds. Any previously scheduled alarm is
193 canceled (only one alarm can be scheduled at any time). The returned value is
194 then the number of seconds before any previously set alarm was to have been
195 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
Géry Ogamcfebfef2019-08-06 23:12:22 +0200196 canceled. If the return value is zero, no alarm is currently scheduled.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400197
Géry Ogamcfebfef2019-08-06 23:12:22 +0200198 .. availability:: Unix. See the man page :manpage:`alarm(2)` for further
199 information.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201
202.. function:: getsignal(signalnum)
203
204 Return the current signal handler for the signal *signalnum*. The returned value
205 may be a callable Python object, or one of the special values
206 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
207 :const:`signal.SIG_IGN` means that the signal was previously ignored,
208 :const:`signal.SIG_DFL` means that the default way of handling the signal was
209 previously in use, and ``None`` means that the previous signal handler was not
210 installed from Python.
211
212
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100213.. function:: strsignal(signalnum)
214
215 Return the system description of the signal *signalnum*, such as
216 "Interrupt", "Segmentation fault", etc. Returns :const:`None` if the signal
217 is not recognized.
218
219 .. versionadded:: 3.8
220
221
Antoine Pitrou9d3627e2018-05-04 13:00:50 +0200222.. function:: valid_signals()
223
224 Return the set of valid signal numbers on this platform. This can be
225 less than ``range(1, NSIG)`` if some signals are reserved by the system
226 for internal use.
227
228 .. versionadded:: 3.8
229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231.. function:: pause()
232
233 Cause the process to sleep until a signal is received; the appropriate handler
Géry Ogamcfebfef2019-08-06 23:12:22 +0200234 will then be called. Returns nothing.
235
236 .. availability:: Unix. See the man page :manpage:`signal(2)` for further
237 information.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Ross Lagerwallbc808222011-06-25 12:13:40 +0200239 See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and
240 :func:`sigpending`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200241
242
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800243.. function:: raise_signal(signum)
244
245 Sends a signal to the calling process. Returns nothing.
246
247 .. versionadded:: 3.8
248
249
Benjamin Peterson74834512019-11-19 20:39:14 -0800250.. function:: pidfd_send_signal(pidfd, sig, siginfo=None, flags=0)
251
252 Send signal *sig* to the process referred to by file descriptor *pidfd*.
253 Python does not currently support the *siginfo* parameter; it must be
254 ``None``. The *flags* argument is provided for future extensions; no flag
255 values are currently defined.
256
257 See the :manpage:`pidfd_send_signal(2)` man page for more information.
258
259 .. availability:: Linux 5.1+
260 .. versionadded:: 3.9
261
262
Tal Einatc7027b72015-05-16 14:14:49 +0300263.. function:: pthread_kill(thread_id, signalnum)
Victor Stinnerb3e72192011-05-08 01:46:11 +0200264
Tal Einatc7027b72015-05-16 14:14:49 +0300265 Send the signal *signalnum* to the thread *thread_id*, another thread in the
Antoine Pitrou682d4432012-03-31 21:09:00 +0200266 same process as the caller. The target thread can be executing any code
267 (Python or not). However, if the target thread is executing the Python
268 interpreter, the Python signal handlers will be :ref:`executed by the main
Tal Einatc7027b72015-05-16 14:14:49 +0300269 thread <signals-and-threads>`. Therefore, the only point of sending a
270 signal to a particular Python thread would be to force a running system call
271 to fail with :exc:`InterruptedError`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200272
Victor Stinner2a129742011-05-30 23:02:52 +0200273 Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
Antoine Pitrou682d4432012-03-31 21:09:00 +0200274 attribute of :class:`threading.Thread` objects to get a suitable value
275 for *thread_id*.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200276
Tal Einatc7027b72015-05-16 14:14:49 +0300277 If *signalnum* is 0, then no signal is sent, but error checking is still
Antoine Pitrou682d4432012-03-31 21:09:00 +0200278 performed; this can be used to check if the target thread is still running.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200279
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800280 .. audit-event:: signal.pthread_kill thread_id,signalnum signal.pthread_kill
281
Géry Ogamcfebfef2019-08-06 23:12:22 +0200282 .. availability:: Unix. See the man page :manpage:`pthread_kill(3)` for further
283 information.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200284
285 See also :func:`os.kill`.
286
287 .. versionadded:: 3.3
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Victor Stinnera9293352011-04-30 15:21:58 +0200290.. function:: pthread_sigmask(how, mask)
291
292 Fetch and/or change the signal mask of the calling thread. The signal mask
293 is the set of signals whose delivery is currently blocked for the caller.
Victor Stinner35b300c2011-05-04 13:20:35 +0200294 Return the old signal mask as a set of signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200295
296 The behavior of the call is dependent on the value of *how*, as follows.
297
Antoine Pitrou8bbe9b42012-03-31 21:09:53 +0200298 * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
299 set and the *mask* argument.
300 * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
301 set of blocked signals. It is permissible to attempt to unblock a
302 signal which is not blocked.
303 * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
304 argument.
Victor Stinnera9293352011-04-30 15:21:58 +0200305
Victor Stinner35b300c2011-05-04 13:20:35 +0200306 *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
Antoine Pitrou9d3627e2018-05-04 13:00:50 +0200307 :const:`signal.SIGTERM`}). Use :func:`~signal.valid_signals` for a full
308 mask including all signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200309
310 For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
311 signal mask of the calling thread.
312
Géry Ogamcfebfef2019-08-06 23:12:22 +0200313 .. availability:: Unix. See the man page :manpage:`sigprocmask(3)` and
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400314 :manpage:`pthread_sigmask(3)` for further information.
Victor Stinnera9293352011-04-30 15:21:58 +0200315
Victor Stinnerb3e72192011-05-08 01:46:11 +0200316 See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
317
Victor Stinnera9293352011-04-30 15:21:58 +0200318 .. versionadded:: 3.3
319
320
Victor Stinneref611c92017-10-13 13:49:43 -0700321.. function:: setitimer(which, seconds, interval=0.0)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000322
Georg Brandl48310cd2009-01-03 21:18:54 +0000323 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000325 by *which* to fire after *seconds* (float is accepted, different from
Victor Stinneref611c92017-10-13 13:49:43 -0700326 :func:`alarm`) and after that every *interval* seconds (if *interval*
327 is non-zero). The interval timer specified by *which* can be cleared by
328 setting *seconds* to zero.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000329
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000330 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000331 The signal sent is dependent on the timer being used;
332 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000333 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
334 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
335
Martin v. Löwis823725e2008-03-24 13:39:54 +0000336 The old values are returned as a tuple: (delay, interval).
337
Georg Brandl495f7b52009-10-27 15:28:25 +0000338 Attempting to pass an invalid interval timer will cause an
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400339 :exc:`ItimerError`.
340
341 .. availability:: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000342
Martin v. Löwis823725e2008-03-24 13:39:54 +0000343
344.. function:: getitimer(which)
345
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000346 Returns current value of a given interval timer specified by *which*.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400347
348 .. availability:: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000349
Martin v. Löwis823725e2008-03-24 13:39:54 +0000350
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800351.. function:: set_wakeup_fd(fd, *, warn_on_full_buffer=True)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000352
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200353 Set the wakeup file descriptor to *fd*. When a signal is received, the
354 signal number is written as a single byte into the fd. This can be used by
355 a library to wakeup a poll or select call, allowing the signal to be fully
356 processed.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000357
Antoine Pitroud79c1d42017-06-13 10:14:09 +0200358 The old wakeup fd is returned (or -1 if file descriptor wakeup was not
359 enabled). If *fd* is -1, file descriptor wakeup is disabled.
360 If not -1, *fd* must be non-blocking. It is up to the library to remove
361 any bytes from *fd* before calling poll or select again.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000362
363 When threads are enabled, this function can only be called from the main thread;
364 attempting to call it from other threads will cause a :exc:`ValueError`
365 exception to be raised.
366
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800367 There are two common ways to use this function. In both approaches,
368 you use the fd to wake up when a signal arrives, but then they
369 differ in how they determine *which* signal or signals have
370 arrived.
371
372 In the first approach, we read the data out of the fd's buffer, and
373 the byte values give you the signal numbers. This is simple, but in
374 rare cases it can run into a problem: generally the fd will have a
375 limited amount of buffer space, and if too many signals arrive too
376 quickly, then the buffer may become full, and some signals may be
377 lost. If you use this approach, then you should set
378 ``warn_on_full_buffer=True``, which will at least cause a warning
379 to be printed to stderr when signals are lost.
380
381 In the second approach, we use the wakeup fd *only* for wakeups,
382 and ignore the actual byte values. In this case, all we care about
383 is whether the fd's buffer is empty or non-empty; a full buffer
384 doesn't indicate a problem at all. If you use this approach, then
385 you should set ``warn_on_full_buffer=False``, so that your users
386 are not confused by spurious warning messages.
387
Victor Stinner11517102014-07-29 23:31:34 +0200388 .. versionchanged:: 3.5
389 On Windows, the function now also supports socket handles.
390
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800391 .. versionchanged:: 3.7
392 Added ``warn_on_full_buffer`` parameter.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000393
Christian Heimes8640e742008-02-23 16:23:06 +0000394.. function:: siginterrupt(signalnum, flag)
395
Georg Brandl18244152009-09-02 20:34:52 +0000396 Change system call restart behaviour: if *flag* is :const:`False`, system
397 calls will be restarted when interrupted by signal *signalnum*, otherwise
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400398 system calls will be interrupted. Returns nothing.
399
Géry Ogamcfebfef2019-08-06 23:12:22 +0200400 .. availability:: Unix. See the man page :manpage:`siginterrupt(3)`
401 for further information.
Georg Brandl48310cd2009-01-03 21:18:54 +0000402
Georg Brandl18244152009-09-02 20:34:52 +0000403 Note that installing a signal handler with :func:`signal` will reset the
404 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000405 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000406
Christian Heimes8640e742008-02-23 16:23:06 +0000407
Georg Brandl116aa622007-08-15 14:28:22 +0000408.. function:: signal(signalnum, handler)
409
410 Set the handler for signal *signalnum* to the function *handler*. *handler* can
411 be a callable Python object taking two arguments (see below), or one of the
412 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
413 signal handler will be returned (see the description of :func:`getsignal`
Géry Ogamcfebfef2019-08-06 23:12:22 +0200414 above). (See the Unix man page :manpage:`signal(2)` for further information.)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416 When threads are enabled, this function can only be called from the main thread;
417 attempting to call it from other threads will cause a :exc:`ValueError`
418 exception to be raised.
419
420 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000421 stack frame (``None`` or a frame object; for a description of frame objects,
422 see the :ref:`description in the type hierarchy <frame-objects>` or see the
423 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Brian Curtinef9efbd2010-08-06 19:27:32 +0000425 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
Berker Peksag219a0122016-11-25 19:46:57 +0300426 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`,
427 :const:`SIGTERM`, or :const:`SIGBREAK`.
428 A :exc:`ValueError` will be raised in any other case.
Berker Peksag77e543c2016-04-24 02:59:16 +0300429 Note that not all systems define the same set of signal names; an
430 :exc:`AttributeError` will be raised if a signal name is not defined as
431 ``SIG*`` module level constant.
Brian Curtinef9efbd2010-08-06 19:27:32 +0000432
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Victor Stinnerb3e72192011-05-08 01:46:11 +0200434.. function:: sigpending()
435
436 Examine the set of signals that are pending for delivery to the calling
437 thread (i.e., the signals which have been raised while blocked). Return the
438 set of the pending signals.
439
Géry Ogamcfebfef2019-08-06 23:12:22 +0200440 .. availability:: Unix. See the man page :manpage:`sigpending(2)` for further
441 information.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200442
443 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
444
445 .. versionadded:: 3.3
446
447
448.. function:: sigwait(sigset)
449
450 Suspend execution of the calling thread until the delivery of one of the
451 signals specified in the signal set *sigset*. The function accepts the signal
452 (removes it from the pending list of signals), and returns the signal number.
453
Géry Ogamcfebfef2019-08-06 23:12:22 +0200454 .. availability:: Unix. See the man page :manpage:`sigwait(3)` for further
455 information.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200456
Ross Lagerwallbc808222011-06-25 12:13:40 +0200457 See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`,
458 :func:`sigwaitinfo` and :func:`sigtimedwait`.
459
460 .. versionadded:: 3.3
461
462
463.. function:: sigwaitinfo(sigset)
464
465 Suspend execution of the calling thread until the delivery of one of the
466 signals specified in the signal set *sigset*. The function accepts the
467 signal and removes it from the pending list of signals. If one of the
468 signals in *sigset* is already pending for the calling thread, the function
469 will return immediately with information about that signal. The signal
470 handler is not called for the delivered signal. The function raises an
Antoine Pitrou767c0a82011-10-23 23:52:23 +0200471 :exc:`InterruptedError` if it is interrupted by a signal that is not in
472 *sigset*.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200473
474 The return value is an object representing the data contained in the
475 :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`,
476 :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`,
477 :attr:`si_band`.
478
Géry Ogamcfebfef2019-08-06 23:12:22 +0200479 .. availability:: Unix. See the man page :manpage:`sigwaitinfo(2)` for further
480 information.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200481
482 See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`.
483
484 .. versionadded:: 3.3
485
Victor Stinnera453cd82015-03-20 12:54:28 +0100486 .. versionchanged:: 3.5
487 The function is now retried if interrupted by a signal not in *sigset*
488 and the signal handler does not raise an exception (see :pep:`475` for
489 the rationale).
490
Ross Lagerwallbc808222011-06-25 12:13:40 +0200491
Victor Stinner643cd682012-03-02 22:54:03 +0100492.. function:: sigtimedwait(sigset, timeout)
Ross Lagerwallbc808222011-06-25 12:13:40 +0200493
Victor Stinner643cd682012-03-02 22:54:03 +0100494 Like :func:`sigwaitinfo`, but takes an additional *timeout* argument
495 specifying a timeout. If *timeout* is specified as :const:`0`, a poll is
496 performed. Returns :const:`None` if a timeout occurs.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200497
Géry Ogamcfebfef2019-08-06 23:12:22 +0200498 .. availability:: Unix. See the man page :manpage:`sigtimedwait(2)` for further
499 information.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200500
501 See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200502
503 .. versionadded:: 3.3
504
Victor Stinnera453cd82015-03-20 12:54:28 +0100505 .. versionchanged:: 3.5
Victor Stinnereb011cb2015-03-31 12:19:15 +0200506 The function is now retried with the recomputed *timeout* if interrupted
507 by a signal not in *sigset* and the signal handler does not raise an
Victor Stinnera453cd82015-03-20 12:54:28 +0100508 exception (see :pep:`475` for the rationale).
509
Victor Stinnerb3e72192011-05-08 01:46:11 +0200510
Georg Brandl116aa622007-08-15 14:28:22 +0000511.. _signal-example:
512
513Example
514-------
515
516Here is a minimal example program. It uses the :func:`alarm` function to limit
517the time spent waiting to open a file; this is useful if the file is for a
518serial device that may not be turned on, which would normally cause the
519:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
520before opening the file; if the operation takes too long, the alarm signal will
521be sent, and the handler raises an exception. ::
522
523 import signal, os
524
525 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000526 print('Signal handler called with signal', signum)
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200527 raise OSError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529 # Set the signal handler and a 5-second alarm
530 signal.signal(signal.SIGALRM, handler)
531 signal.alarm(5)
532
533 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000534 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536 signal.alarm(0) # Disable the alarm
537
Alfred Perlsteina2510732018-08-17 09:48:05 -0400538Note on SIGPIPE
539---------------
540
541Piping output of your program to tools like :manpage:`head(1)` will
542cause a :const:`SIGPIPE` signal to be sent to your process when the receiver
543of its standard output closes early. This results in an exception
544like :code:`BrokenPipeError: [Errno 32] Broken pipe`. To handle this
545case, wrap your entry point to catch this exception as follows::
546
547 import os
548 import sys
549
550 def main():
551 try:
552 # simulate large output (your code replaces this loop)
553 for x in range(10000):
554 print("y")
555 # flush output here to force SIGPIPE to be triggered
556 # while inside this try block.
557 sys.stdout.flush()
558 except BrokenPipeError:
559 # Python flushes standard streams on exit; redirect remaining output
560 # to devnull to avoid another BrokenPipeError at shutdown
561 devnull = os.open(os.devnull, os.O_WRONLY)
562 os.dup2(devnull, sys.stdout.fileno())
563 sys.exit(1) # Python exits with error code 1 on EPIPE
564
565 if __name__ == '__main__':
566 main()
567
568Do not set :const:`SIGPIPE`'s disposition to :const:`SIG_DFL`
569in order to avoid :exc:`BrokenPipeError`. Doing that would cause
570your program to exit unexpectedly also whenever any socket connection
571is interrupted while your program is still writing to it.