blob: d02a0a8e3c8cb464b302a467db1a18d6c6917a87 [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
7
Antoine Pitrou6afd11c2012-03-31 20:56:21 +02008This module provides mechanisms to use signal handlers in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00009
Georg Brandl116aa622007-08-15 14:28:22 +000010
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020011General rules
12-------------
Georg Brandl116aa622007-08-15 14:28:22 +000013
Martin Panterc04fb562016-02-10 05:44:01 +000014The :func:`signal.signal` function allows defining custom handlers to be
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020015executed when a signal is received. A small number of default handlers are
16installed: :const:`SIGPIPE` is ignored (so write errors on pipes and sockets
17can be reported as ordinary Python exceptions) and :const:`SIGINT` is
18translated into a :exc:`KeyboardInterrupt` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000019
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020020A handler for a particular signal, once set, remains installed until it is
21explicitly reset (Python emulates the BSD style interface regardless of the
22underlying implementation), with the exception of the handler for
23:const:`SIGCHLD`, which follows the underlying implementation.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Georg Brandl116aa622007-08-15 14:28:22 +000025
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020026Execution of Python signal handlers
27^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28
29A Python signal handler does not get executed inside the low-level (C) signal
30handler. Instead, the low-level signal handler sets a flag which tells the
31:term:`virtual machine` to execute the corresponding Python signal handler
32at a later point(for example at the next :term:`bytecode` instruction).
33This has consequences:
34
35* It makes little sense to catch synchronous errors like :const:`SIGFPE` or
Georg Brandlc377fe22013-10-06 21:22:42 +020036 :const:`SIGSEGV` that are caused by an invalid operation in C code. Python
37 will return from the signal handler to the C code, which is likely to raise
38 the same signal again, causing Python to apparently hang. From Python 3.3
39 onwards, you can use the :mod:`faulthandler` module to report on synchronous
40 errors.
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020041
42* A long-running calculation implemented purely in C (such as regular
43 expression matching on a large body of text) may run uninterrupted for an
44 arbitrary amount of time, regardless of any signals received. The Python
45 signal handlers will be called when the calculation finishes.
46
47
Antoine Pitrou682d4432012-03-31 21:09:00 +020048.. _signals-and-threads:
49
50
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020051Signals and threads
52^^^^^^^^^^^^^^^^^^^
53
54Python signal handlers are always executed in the main Python thread,
55even if the signal was received in another thread. This means that signals
56can't be used as a means of inter-thread communication. You can use
57the synchronization primitives from the :mod:`threading` module instead.
58
59Besides, only the main thread is allowed to set a new signal handler.
60
61
62Module contents
63---------------
Georg Brandl116aa622007-08-15 14:28:22 +000064
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020065.. versionchanged:: 3.5
66 signal (SIG*), handler (:const:`SIG_DFL`, :const:`SIG_IGN`) and sigmask
67 (:const:`SIG_BLOCK`, :const:`SIG_UNBLOCK`, :const:`SIG_SETMASK`)
68 related constants listed below were turned into
69 :class:`enums <enum.IntEnum>`.
70 :func:`getsignal`, :func:`pthread_sigmask`, :func:`sigpending` and
71 :func:`sigwait` functions return human-readable
72 :class:`enums <enum.IntEnum>`.
73
74
Georg Brandl116aa622007-08-15 14:28:22 +000075The variables defined in the :mod:`signal` module are:
76
77
78.. data:: SIG_DFL
79
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000080 This is one of two standard signal handling options; it will simply perform
81 the default function for the signal. For example, on most systems the
82 default action for :const:`SIGQUIT` is to dump core and exit, while the
83 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85
86.. data:: SIG_IGN
87
88 This is another standard signal handler, which will simply ignore the given
89 signal.
90
91
92.. data:: SIG*
93
94 All the signal numbers are defined symbolically. For example, the hangup signal
95 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
96 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Georg Brandl60203b42010-10-06 10:11:56 +000097 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +000098 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
99 not all systems define the same set of signal names; only those names defined by
100 the system are defined by this module.
101
102
Brian Curtineb24d742010-04-12 17:16:38 +0000103.. data:: CTRL_C_EVENT
104
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300105 The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000106 only be used with :func:`os.kill`.
107
Brian Curtineb24d742010-04-12 17:16:38 +0000108 Availability: Windows.
109
Brian Curtin904bd392010-04-20 15:28:06 +0000110 .. versionadded:: 3.2
111
Brian Curtineb24d742010-04-12 17:16:38 +0000112
113.. data:: CTRL_BREAK_EVENT
114
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300115 The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000116 only be used with :func:`os.kill`.
117
Brian Curtineb24d742010-04-12 17:16:38 +0000118 Availability: Windows.
119
Brian Curtin904bd392010-04-20 15:28:06 +0000120 .. versionadded:: 3.2
121
Brian Curtineb24d742010-04-12 17:16:38 +0000122
Georg Brandl116aa622007-08-15 14:28:22 +0000123.. data:: NSIG
124
125 One more than the number of the highest signal number.
126
Martin v. Löwis823725e2008-03-24 13:39:54 +0000127
Georg Brandl48310cd2009-01-03 21:18:54 +0000128.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000129
Georg Brandl18244152009-09-02 20:34:52 +0000130 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
131 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000132
133
Georg Brandl48310cd2009-01-03 21:18:54 +0000134.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000135
Georg Brandl48310cd2009-01-03 21:18:54 +0000136 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000137 SIGVTALRM upon expiration.
138
139
140.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000141
142 Decrements interval timer both when the process executes and when the
143 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
144 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000145 in user and kernel space. SIGPROF is delivered upon expiration.
146
147
Victor Stinnera9293352011-04-30 15:21:58 +0200148.. data:: SIG_BLOCK
149
150 A possible value for the *how* parameter to :func:`pthread_sigmask`
151 indicating that signals are to be blocked.
152
153 .. versionadded:: 3.3
154
155.. data:: SIG_UNBLOCK
156
157 A possible value for the *how* parameter to :func:`pthread_sigmask`
158 indicating that signals are to be unblocked.
159
160 .. versionadded:: 3.3
161
162.. data:: SIG_SETMASK
163
164 A possible value for the *how* parameter to :func:`pthread_sigmask`
165 indicating that the signal mask is to be replaced.
166
167 .. versionadded:: 3.3
168
169
Martin v. Löwis823725e2008-03-24 13:39:54 +0000170The :mod:`signal` module defines one exception:
171
172.. exception:: ItimerError
173
174 Raised to signal an error from the underlying :func:`setitimer` or
175 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000176 interval timer or a negative time is passed to :func:`setitimer`.
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200177 This error is a subtype of :exc:`OSError`.
178
179 .. versionadded:: 3.3
180 This error used to be a subtype of :exc:`IOError`, which is now an
181 alias of :exc:`OSError`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000182
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184The :mod:`signal` module defines the following functions:
185
186
187.. function:: alarm(time)
188
189 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
190 sent to the process in *time* seconds. Any previously scheduled alarm is
191 canceled (only one alarm can be scheduled at any time). The returned value is
192 then the number of seconds before any previously set alarm was to have been
193 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
194 canceled. If the return value is zero, no alarm is currently scheduled. (See
195 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
196
197
198.. function:: getsignal(signalnum)
199
200 Return the current signal handler for the signal *signalnum*. The returned value
201 may be a callable Python object, or one of the special values
202 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
203 :const:`signal.SIG_IGN` means that the signal was previously ignored,
204 :const:`signal.SIG_DFL` means that the default way of handling the signal was
205 previously in use, and ``None`` means that the previous signal handler was not
206 installed from Python.
207
208
209.. function:: pause()
210
211 Cause the process to sleep until a signal is received; the appropriate handler
212 will then be called. Returns nothing. Not on Windows. (See the Unix man page
213 :manpage:`signal(2)`.)
214
Ross Lagerwallbc808222011-06-25 12:13:40 +0200215 See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and
216 :func:`sigpending`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200217
218
Tal Einatc7027b72015-05-16 14:14:49 +0300219.. function:: pthread_kill(thread_id, signalnum)
Victor Stinnerb3e72192011-05-08 01:46:11 +0200220
Tal Einatc7027b72015-05-16 14:14:49 +0300221 Send the signal *signalnum* to the thread *thread_id*, another thread in the
Antoine Pitrou682d4432012-03-31 21:09:00 +0200222 same process as the caller. The target thread can be executing any code
223 (Python or not). However, if the target thread is executing the Python
224 interpreter, the Python signal handlers will be :ref:`executed by the main
Tal Einatc7027b72015-05-16 14:14:49 +0300225 thread <signals-and-threads>`. Therefore, the only point of sending a
226 signal to a particular Python thread would be to force a running system call
227 to fail with :exc:`InterruptedError`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200228
Victor Stinner2a129742011-05-30 23:02:52 +0200229 Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
Antoine Pitrou682d4432012-03-31 21:09:00 +0200230 attribute of :class:`threading.Thread` objects to get a suitable value
231 for *thread_id*.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200232
Tal Einatc7027b72015-05-16 14:14:49 +0300233 If *signalnum* is 0, then no signal is sent, but error checking is still
Antoine Pitrou682d4432012-03-31 21:09:00 +0200234 performed; this can be used to check if the target thread is still running.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200235
236 Availability: Unix (see the man page :manpage:`pthread_kill(3)` for further
237 information).
238
239 See also :func:`os.kill`.
240
241 .. versionadded:: 3.3
242
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Victor Stinnera9293352011-04-30 15:21:58 +0200244.. function:: pthread_sigmask(how, mask)
245
246 Fetch and/or change the signal mask of the calling thread. The signal mask
247 is the set of signals whose delivery is currently blocked for the caller.
Victor Stinner35b300c2011-05-04 13:20:35 +0200248 Return the old signal mask as a set of signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200249
250 The behavior of the call is dependent on the value of *how*, as follows.
251
Antoine Pitrou8bbe9b42012-03-31 21:09:53 +0200252 * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
253 set and the *mask* argument.
254 * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
255 set of blocked signals. It is permissible to attempt to unblock a
256 signal which is not blocked.
257 * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
258 argument.
Victor Stinnera9293352011-04-30 15:21:58 +0200259
Victor Stinner35b300c2011-05-04 13:20:35 +0200260 *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
261 :const:`signal.SIGTERM`}). Use ``range(1, signal.NSIG)`` for a full mask
262 including all signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200263
264 For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
265 signal mask of the calling thread.
266
267 Availability: Unix. See the man page :manpage:`sigprocmask(3)` and
268 :manpage:`pthread_sigmask(3)` for further information.
269
Victor Stinnerb3e72192011-05-08 01:46:11 +0200270 See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
271
Victor Stinnera9293352011-04-30 15:21:58 +0200272 .. versionadded:: 3.3
273
274
Martin v. Löwis823725e2008-03-24 13:39:54 +0000275.. function:: setitimer(which, seconds[, interval])
276
Georg Brandl48310cd2009-01-03 21:18:54 +0000277 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000278 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000279 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000280 :func:`alarm`) and after that every *interval* seconds. The interval
281 timer specified by *which* can be cleared by setting seconds to zero.
282
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000283 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000284 The signal sent is dependent on the timer being used;
285 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000286 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
287 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
288
Martin v. Löwis823725e2008-03-24 13:39:54 +0000289 The old values are returned as a tuple: (delay, interval).
290
Georg Brandl495f7b52009-10-27 15:28:25 +0000291 Attempting to pass an invalid interval timer will cause an
292 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000293
Martin v. Löwis823725e2008-03-24 13:39:54 +0000294
295.. function:: getitimer(which)
296
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000297 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000298 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000299
Martin v. Löwis823725e2008-03-24 13:39:54 +0000300
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000301.. function:: set_wakeup_fd(fd)
302
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200303 Set the wakeup file descriptor to *fd*. When a signal is received, the
304 signal number is written as a single byte into the fd. This can be used by
305 a library to wakeup a poll or select call, allowing the signal to be fully
306 processed.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000307
308 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
309 library to remove any bytes before calling poll or select again.
310
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200311 Use for example ``struct.unpack('%uB' % len(data), data)`` to decode the
312 signal numbers list.
313
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000314 When threads are enabled, this function can only be called from the main thread;
315 attempting to call it from other threads will cause a :exc:`ValueError`
316 exception to be raised.
317
Victor Stinner11517102014-07-29 23:31:34 +0200318 .. versionchanged:: 3.5
319 On Windows, the function now also supports socket handles.
320
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000321
Christian Heimes8640e742008-02-23 16:23:06 +0000322.. function:: siginterrupt(signalnum, flag)
323
Georg Brandl18244152009-09-02 20:34:52 +0000324 Change system call restart behaviour: if *flag* is :const:`False`, system
325 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000326 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000327 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000328
Georg Brandl18244152009-09-02 20:34:52 +0000329 Note that installing a signal handler with :func:`signal` will reset the
330 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000331 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000332
Christian Heimes8640e742008-02-23 16:23:06 +0000333
Georg Brandl116aa622007-08-15 14:28:22 +0000334.. function:: signal(signalnum, handler)
335
336 Set the handler for signal *signalnum* to the function *handler*. *handler* can
337 be a callable Python object taking two arguments (see below), or one of the
338 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
339 signal handler will be returned (see the description of :func:`getsignal`
340 above). (See the Unix man page :manpage:`signal(2)`.)
341
342 When threads are enabled, this function can only be called from the main thread;
343 attempting to call it from other threads will cause a :exc:`ValueError`
344 exception to be raised.
345
346 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000347 stack frame (``None`` or a frame object; for a description of frame objects,
348 see the :ref:`description in the type hierarchy <frame-objects>` or see the
349 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Brian Curtinef9efbd2010-08-06 19:27:32 +0000351 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
352 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
353 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
Berker Peksag77e543c2016-04-24 02:59:16 +0300354 Note that not all systems define the same set of signal names; an
355 :exc:`AttributeError` will be raised if a signal name is not defined as
356 ``SIG*`` module level constant.
Brian Curtinef9efbd2010-08-06 19:27:32 +0000357
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Victor Stinnerb3e72192011-05-08 01:46:11 +0200359.. function:: sigpending()
360
361 Examine the set of signals that are pending for delivery to the calling
362 thread (i.e., the signals which have been raised while blocked). Return the
363 set of the pending signals.
364
365 Availability: Unix (see the man page :manpage:`sigpending(2)` for further
366 information).
367
368 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
369
370 .. versionadded:: 3.3
371
372
373.. function:: sigwait(sigset)
374
375 Suspend execution of the calling thread until the delivery of one of the
376 signals specified in the signal set *sigset*. The function accepts the signal
377 (removes it from the pending list of signals), and returns the signal number.
378
379 Availability: Unix (see the man page :manpage:`sigwait(3)` for further
380 information).
381
Ross Lagerwallbc808222011-06-25 12:13:40 +0200382 See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`,
383 :func:`sigwaitinfo` and :func:`sigtimedwait`.
384
385 .. versionadded:: 3.3
386
387
388.. function:: sigwaitinfo(sigset)
389
390 Suspend execution of the calling thread until the delivery of one of the
391 signals specified in the signal set *sigset*. The function accepts the
392 signal and removes it from the pending list of signals. If one of the
393 signals in *sigset* is already pending for the calling thread, the function
394 will return immediately with information about that signal. The signal
395 handler is not called for the delivered signal. The function raises an
Antoine Pitrou767c0a82011-10-23 23:52:23 +0200396 :exc:`InterruptedError` if it is interrupted by a signal that is not in
397 *sigset*.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200398
399 The return value is an object representing the data contained in the
400 :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`,
401 :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`,
402 :attr:`si_band`.
403
404 Availability: Unix (see the man page :manpage:`sigwaitinfo(2)` for further
405 information).
406
407 See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`.
408
409 .. versionadded:: 3.3
410
Victor Stinnera453cd82015-03-20 12:54:28 +0100411 .. versionchanged:: 3.5
412 The function is now retried if interrupted by a signal not in *sigset*
413 and the signal handler does not raise an exception (see :pep:`475` for
414 the rationale).
415
Ross Lagerwallbc808222011-06-25 12:13:40 +0200416
Victor Stinner643cd682012-03-02 22:54:03 +0100417.. function:: sigtimedwait(sigset, timeout)
Ross Lagerwallbc808222011-06-25 12:13:40 +0200418
Victor Stinner643cd682012-03-02 22:54:03 +0100419 Like :func:`sigwaitinfo`, but takes an additional *timeout* argument
420 specifying a timeout. If *timeout* is specified as :const:`0`, a poll is
421 performed. Returns :const:`None` if a timeout occurs.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200422
423 Availability: Unix (see the man page :manpage:`sigtimedwait(2)` for further
424 information).
425
426 See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200427
428 .. versionadded:: 3.3
429
Victor Stinnera453cd82015-03-20 12:54:28 +0100430 .. versionchanged:: 3.5
Victor Stinnereb011cb2015-03-31 12:19:15 +0200431 The function is now retried with the recomputed *timeout* if interrupted
432 by a signal not in *sigset* and the signal handler does not raise an
Victor Stinnera453cd82015-03-20 12:54:28 +0100433 exception (see :pep:`475` for the rationale).
434
Victor Stinnerb3e72192011-05-08 01:46:11 +0200435
Georg Brandl116aa622007-08-15 14:28:22 +0000436.. _signal-example:
437
438Example
439-------
440
441Here is a minimal example program. It uses the :func:`alarm` function to limit
442the time spent waiting to open a file; this is useful if the file is for a
443serial device that may not be turned on, which would normally cause the
444:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
445before opening the file; if the operation takes too long, the alarm signal will
446be sent, and the handler raises an exception. ::
447
448 import signal, os
449
450 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000451 print('Signal handler called with signal', signum)
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200452 raise OSError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454 # Set the signal handler and a 5-second alarm
455 signal.signal(signal.SIGALRM, handler)
456 signal.alarm(5)
457
458 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000459 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461 signal.alarm(0) # Disable the alarm
462