blob: 61252ce4e807ec55794b9b5de479d8d15ab783b4 [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
19translated into a :exc:`KeyboardInterrupt` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000020
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020021A handler for a particular signal, once set, remains installed until it is
22explicitly reset (Python emulates the BSD style interface regardless of the
23underlying implementation), with the exception of the handler for
24:const:`SIGCHLD`, which follows the underlying implementation.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandl116aa622007-08-15 14:28:22 +000026
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020027Execution of Python signal handlers
28^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
29
30A Python signal handler does not get executed inside the low-level (C) signal
31handler. Instead, the low-level signal handler sets a flag which tells the
32:term:`virtual machine` to execute the corresponding Python signal handler
33at a later point(for example at the next :term:`bytecode` instruction).
34This has consequences:
35
36* It makes little sense to catch synchronous errors like :const:`SIGFPE` or
Georg Brandlc377fe22013-10-06 21:22:42 +020037 :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.
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020042
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
Antoine Pitrou682d4432012-03-31 21:09:00 +020049.. _signals-and-threads:
50
51
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020052Signals and threads
53^^^^^^^^^^^^^^^^^^^
54
55Python signal handlers are always executed in the main Python thread,
56even if the signal was received in another thread. This means that signals
57can't be used as a means of inter-thread communication. You can use
58the synchronization primitives from the :mod:`threading` module instead.
59
60Besides, only the main thread is allowed to set a new signal handler.
61
62
63Module contents
64---------------
Georg Brandl116aa622007-08-15 14:28:22 +000065
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020066.. 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
Georg Brandl116aa622007-08-15 14:28:22 +000076The variables defined in the :mod:`signal` module are:
77
78
79.. data:: SIG_DFL
80
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000081 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.
Georg Brandl116aa622007-08-15 14:28:22 +000085
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
Georg Brandl60203b42010-10-06 10:11:56 +000098 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +000099 :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
Brian Curtineb24d742010-04-12 17:16:38 +0000104.. data:: CTRL_C_EVENT
105
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300106 The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000107 only be used with :func:`os.kill`.
108
Brian Curtineb24d742010-04-12 17:16:38 +0000109 Availability: Windows.
110
Brian Curtin904bd392010-04-20 15:28:06 +0000111 .. versionadded:: 3.2
112
Brian Curtineb24d742010-04-12 17:16:38 +0000113
114.. data:: CTRL_BREAK_EVENT
115
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300116 The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can
Brian Curtinf045d772010-08-05 18:56:00 +0000117 only be used with :func:`os.kill`.
118
Brian Curtineb24d742010-04-12 17:16:38 +0000119 Availability: Windows.
120
Brian Curtin904bd392010-04-20 15:28:06 +0000121 .. versionadded:: 3.2
122
Brian Curtineb24d742010-04-12 17:16:38 +0000123
Georg Brandl116aa622007-08-15 14:28:22 +0000124.. data:: NSIG
125
126 One more than the number of the highest signal number.
127
Martin v. Löwis823725e2008-03-24 13:39:54 +0000128
Georg Brandl48310cd2009-01-03 21:18:54 +0000129.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000130
Georg Brandl18244152009-09-02 20:34:52 +0000131 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
132 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000133
134
Georg Brandl48310cd2009-01-03 21:18:54 +0000135.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000136
Georg Brandl48310cd2009-01-03 21:18:54 +0000137 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000138 SIGVTALRM upon expiration.
139
140
141.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000142
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
Martin v. Löwis823725e2008-03-24 13:39:54 +0000146 in user and kernel space. SIGPROF is delivered upon expiration.
147
148
Victor Stinnera9293352011-04-30 15:21:58 +0200149.. 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
Martin v. Löwis823725e2008-03-24 13:39:54 +0000171The :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
Georg Brandl48310cd2009-01-03 21:18:54 +0000177 interval timer or a negative time is passed to :func:`setitimer`.
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200178 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`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000183
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185The :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)`.) Availability: Unix.
197
198
199.. function:: getsignal(signalnum)
200
201 Return the current signal handler for the signal *signalnum*. The returned value
202 may be a callable Python object, or one of the special values
203 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
204 :const:`signal.SIG_IGN` means that the signal was previously ignored,
205 :const:`signal.SIG_DFL` means that the default way of handling the signal was
206 previously in use, and ``None`` means that the previous signal handler was not
207 installed from Python.
208
209
210.. function:: pause()
211
212 Cause the process to sleep until a signal is received; the appropriate handler
213 will then be called. Returns nothing. Not on Windows. (See the Unix man page
214 :manpage:`signal(2)`.)
215
Ross Lagerwallbc808222011-06-25 12:13:40 +0200216 See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and
217 :func:`sigpending`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200218
219
Tal Einatc7027b72015-05-16 14:14:49 +0300220.. function:: pthread_kill(thread_id, signalnum)
Victor Stinnerb3e72192011-05-08 01:46:11 +0200221
Tal Einatc7027b72015-05-16 14:14:49 +0300222 Send the signal *signalnum* to the thread *thread_id*, another thread in the
Antoine Pitrou682d4432012-03-31 21:09:00 +0200223 same process as the caller. The target thread can be executing any code
224 (Python or not). However, if the target thread is executing the Python
225 interpreter, the Python signal handlers will be :ref:`executed by the main
Tal Einatc7027b72015-05-16 14:14:49 +0300226 thread <signals-and-threads>`. Therefore, the only point of sending a
227 signal to a particular Python thread would be to force a running system call
228 to fail with :exc:`InterruptedError`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200229
Victor Stinner2a129742011-05-30 23:02:52 +0200230 Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
Antoine Pitrou682d4432012-03-31 21:09:00 +0200231 attribute of :class:`threading.Thread` objects to get a suitable value
232 for *thread_id*.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200233
Tal Einatc7027b72015-05-16 14:14:49 +0300234 If *signalnum* is 0, then no signal is sent, but error checking is still
Antoine Pitrou682d4432012-03-31 21:09:00 +0200235 performed; this can be used to check if the target thread is still running.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200236
237 Availability: Unix (see the man page :manpage:`pthread_kill(3)` for further
238 information).
239
240 See also :func:`os.kill`.
241
242 .. versionadded:: 3.3
243
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Victor Stinnera9293352011-04-30 15:21:58 +0200245.. function:: pthread_sigmask(how, mask)
246
247 Fetch and/or change the signal mask of the calling thread. The signal mask
248 is the set of signals whose delivery is currently blocked for the caller.
Victor Stinner35b300c2011-05-04 13:20:35 +0200249 Return the old signal mask as a set of signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200250
251 The behavior of the call is dependent on the value of *how*, as follows.
252
Antoine Pitrou8bbe9b42012-03-31 21:09:53 +0200253 * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
254 set and the *mask* argument.
255 * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
256 set of blocked signals. It is permissible to attempt to unblock a
257 signal which is not blocked.
258 * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
259 argument.
Victor Stinnera9293352011-04-30 15:21:58 +0200260
Victor Stinner35b300c2011-05-04 13:20:35 +0200261 *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
262 :const:`signal.SIGTERM`}). Use ``range(1, signal.NSIG)`` for a full mask
263 including all signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200264
265 For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
266 signal mask of the calling thread.
267
268 Availability: Unix. See the man page :manpage:`sigprocmask(3)` and
269 :manpage:`pthread_sigmask(3)` for further information.
270
Victor Stinnerb3e72192011-05-08 01:46:11 +0200271 See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
272
Victor Stinnera9293352011-04-30 15:21:58 +0200273 .. versionadded:: 3.3
274
275
Martin v. Löwis823725e2008-03-24 13:39:54 +0000276.. function:: setitimer(which, seconds[, interval])
277
Georg Brandl48310cd2009-01-03 21:18:54 +0000278 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000279 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000280 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000281 :func:`alarm`) and after that every *interval* seconds. The interval
282 timer specified by *which* can be cleared by setting seconds to zero.
283
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000284 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000285 The signal sent is dependent on the timer being used;
286 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000287 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
288 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
289
Martin v. Löwis823725e2008-03-24 13:39:54 +0000290 The old values are returned as a tuple: (delay, interval).
291
Georg Brandl495f7b52009-10-27 15:28:25 +0000292 Attempting to pass an invalid interval timer will cause an
293 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000294
Martin v. Löwis823725e2008-03-24 13:39:54 +0000295
296.. function:: getitimer(which)
297
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000298 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000299 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000300
Martin v. Löwis823725e2008-03-24 13:39:54 +0000301
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000302.. function:: set_wakeup_fd(fd)
303
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200304 Set the wakeup file descriptor to *fd*. When a signal is received, the
305 signal number is written as a single byte into the fd. This can be used by
306 a library to wakeup a poll or select call, allowing the signal to be fully
307 processed.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000308
309 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
310 library to remove any bytes before calling poll or select again.
311
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200312 Use for example ``struct.unpack('%uB' % len(data), data)`` to decode the
313 signal numbers list.
314
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000315 When threads are enabled, this function can only be called from the main thread;
316 attempting to call it from other threads will cause a :exc:`ValueError`
317 exception to be raised.
318
Victor Stinner11517102014-07-29 23:31:34 +0200319 .. versionchanged:: 3.5
320 On Windows, the function now also supports socket handles.
321
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000322
Christian Heimes8640e742008-02-23 16:23:06 +0000323.. function:: siginterrupt(signalnum, flag)
324
Georg Brandl18244152009-09-02 20:34:52 +0000325 Change system call restart behaviour: if *flag* is :const:`False`, system
326 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000327 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000328 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000329
Georg Brandl18244152009-09-02 20:34:52 +0000330 Note that installing a signal handler with :func:`signal` will reset the
331 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000332 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000333
Christian Heimes8640e742008-02-23 16:23:06 +0000334
Georg Brandl116aa622007-08-15 14:28:22 +0000335.. function:: signal(signalnum, handler)
336
337 Set the handler for signal *signalnum* to the function *handler*. *handler* can
338 be a callable Python object taking two arguments (see below), or one of the
339 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
340 signal handler will be returned (see the description of :func:`getsignal`
341 above). (See the Unix man page :manpage:`signal(2)`.)
342
343 When threads are enabled, this function can only be called from the main thread;
344 attempting to call it from other threads will cause a :exc:`ValueError`
345 exception to be raised.
346
347 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000348 stack frame (``None`` or a frame object; for a description of frame objects,
349 see the :ref:`description in the type hierarchy <frame-objects>` or see the
350 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Brian Curtinef9efbd2010-08-06 19:27:32 +0000352 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
353 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
354 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
Berker Peksag77e543c2016-04-24 02:59:16 +0300355 Note that not all systems define the same set of signal names; an
356 :exc:`AttributeError` will be raised if a signal name is not defined as
357 ``SIG*`` module level constant.
Brian Curtinef9efbd2010-08-06 19:27:32 +0000358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Victor Stinnerb3e72192011-05-08 01:46:11 +0200360.. function:: sigpending()
361
362 Examine the set of signals that are pending for delivery to the calling
363 thread (i.e., the signals which have been raised while blocked). Return the
364 set of the pending signals.
365
366 Availability: Unix (see the man page :manpage:`sigpending(2)` for further
367 information).
368
369 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
370
371 .. versionadded:: 3.3
372
373
374.. function:: sigwait(sigset)
375
376 Suspend execution of the calling thread until the delivery of one of the
377 signals specified in the signal set *sigset*. The function accepts the signal
378 (removes it from the pending list of signals), and returns the signal number.
379
380 Availability: Unix (see the man page :manpage:`sigwait(3)` for further
381 information).
382
Ross Lagerwallbc808222011-06-25 12:13:40 +0200383 See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`,
384 :func:`sigwaitinfo` and :func:`sigtimedwait`.
385
386 .. versionadded:: 3.3
387
388
389.. function:: sigwaitinfo(sigset)
390
391 Suspend execution of the calling thread until the delivery of one of the
392 signals specified in the signal set *sigset*. The function accepts the
393 signal and removes it from the pending list of signals. If one of the
394 signals in *sigset* is already pending for the calling thread, the function
395 will return immediately with information about that signal. The signal
396 handler is not called for the delivered signal. The function raises an
Antoine Pitrou767c0a82011-10-23 23:52:23 +0200397 :exc:`InterruptedError` if it is interrupted by a signal that is not in
398 *sigset*.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200399
400 The return value is an object representing the data contained in the
401 :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`,
402 :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`,
403 :attr:`si_band`.
404
405 Availability: Unix (see the man page :manpage:`sigwaitinfo(2)` for further
406 information).
407
408 See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`.
409
410 .. versionadded:: 3.3
411
Victor Stinnera453cd82015-03-20 12:54:28 +0100412 .. versionchanged:: 3.5
413 The function is now retried if interrupted by a signal not in *sigset*
414 and the signal handler does not raise an exception (see :pep:`475` for
415 the rationale).
416
Ross Lagerwallbc808222011-06-25 12:13:40 +0200417
Victor Stinner643cd682012-03-02 22:54:03 +0100418.. function:: sigtimedwait(sigset, timeout)
Ross Lagerwallbc808222011-06-25 12:13:40 +0200419
Victor Stinner643cd682012-03-02 22:54:03 +0100420 Like :func:`sigwaitinfo`, but takes an additional *timeout* argument
421 specifying a timeout. If *timeout* is specified as :const:`0`, a poll is
422 performed. Returns :const:`None` if a timeout occurs.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200423
424 Availability: Unix (see the man page :manpage:`sigtimedwait(2)` for further
425 information).
426
427 See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200428
429 .. versionadded:: 3.3
430
Victor Stinnera453cd82015-03-20 12:54:28 +0100431 .. versionchanged:: 3.5
Victor Stinnereb011cb2015-03-31 12:19:15 +0200432 The function is now retried with the recomputed *timeout* if interrupted
433 by a signal not in *sigset* and the signal handler does not raise an
Victor Stinnera453cd82015-03-20 12:54:28 +0100434 exception (see :pep:`475` for the rationale).
435
Victor Stinnerb3e72192011-05-08 01:46:11 +0200436
Georg Brandl116aa622007-08-15 14:28:22 +0000437.. _signal-example:
438
439Example
440-------
441
442Here is a minimal example program. It uses the :func:`alarm` function to limit
443the time spent waiting to open a file; this is useful if the file is for a
444serial device that may not be turned on, which would normally cause the
445:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
446before opening the file; if the operation takes too long, the alarm signal will
447be sent, and the handler raises an exception. ::
448
449 import signal, os
450
451 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000452 print('Signal handler called with signal', signum)
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200453 raise OSError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455 # Set the signal handler and a 5-second alarm
456 signal.signal(signal.SIGALRM, handler)
457 signal.alarm(5)
458
459 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000460 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 signal.alarm(0) # Disable the alarm
463