blob: 2a472fe57a4e762105dce21271d81e50e875170f [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
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020014The :func:`signal.signal` function allows to define custom handlers to be
15executed 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
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020025There is no way to "block" signals temporarily from critical sections (since
26this is not supported by all Unix flavors).
Georg Brandl116aa622007-08-15 14:28:22 +000027
Georg Brandl116aa622007-08-15 14:28:22 +000028
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020029Execution of Python signal handlers
30^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
31
32A Python signal handler does not get executed inside the low-level (C) signal
33handler. Instead, the low-level signal handler sets a flag which tells the
34:term:`virtual machine` to execute the corresponding Python signal handler
35at a later point(for example at the next :term:`bytecode` instruction).
36This has consequences:
37
38* It makes little sense to catch synchronous errors like :const:`SIGFPE` or
39 :const:`SIGSEGV`.
40
41* A long-running calculation implemented purely in C (such as regular
42 expression matching on a large body of text) may run uninterrupted for an
43 arbitrary amount of time, regardless of any signals received. The Python
44 signal handlers will be called when the calculation finishes.
45
46
Antoine Pitrou682d4432012-03-31 21:09:00 +020047.. _signals-and-threads:
48
49
Antoine Pitrou6afd11c2012-03-31 20:56:21 +020050Signals and threads
51^^^^^^^^^^^^^^^^^^^
52
53Python signal handlers are always executed in the main Python thread,
54even if the signal was received in another thread. This means that signals
55can't be used as a means of inter-thread communication. You can use
56the synchronization primitives from the :mod:`threading` module instead.
57
58Besides, only the main thread is allowed to set a new signal handler.
59
60
61Module contents
62---------------
Georg Brandl116aa622007-08-15 14:28:22 +000063
64The variables defined in the :mod:`signal` module are:
65
66
67.. data:: SIG_DFL
68
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000069 This is one of two standard signal handling options; it will simply perform
70 the default function for the signal. For example, on most systems the
71 default action for :const:`SIGQUIT` is to dump core and exit, while the
72 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74
75.. data:: SIG_IGN
76
77 This is another standard signal handler, which will simply ignore the given
78 signal.
79
80
81.. data:: SIG*
82
83 All the signal numbers are defined symbolically. For example, the hangup signal
84 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
85 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Georg Brandl60203b42010-10-06 10:11:56 +000086 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +000087 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
88 not all systems define the same set of signal names; only those names defined by
89 the system are defined by this module.
90
91
Brian Curtineb24d742010-04-12 17:16:38 +000092.. data:: CTRL_C_EVENT
93
Brian Curtinf045d772010-08-05 18:56:00 +000094 The signal corresponding to the CTRL+C keystroke event. This signal can
95 only be used with :func:`os.kill`.
96
Brian Curtineb24d742010-04-12 17:16:38 +000097 Availability: Windows.
98
Brian Curtin904bd392010-04-20 15:28:06 +000099 .. versionadded:: 3.2
100
Brian Curtineb24d742010-04-12 17:16:38 +0000101
102.. data:: CTRL_BREAK_EVENT
103
Brian Curtinf045d772010-08-05 18:56:00 +0000104 The signal corresponding to the CTRL+BREAK keystroke event. This signal can
105 only be used with :func:`os.kill`.
106
Brian Curtineb24d742010-04-12 17:16:38 +0000107 Availability: Windows.
108
Brian Curtin904bd392010-04-20 15:28:06 +0000109 .. versionadded:: 3.2
110
Brian Curtineb24d742010-04-12 17:16:38 +0000111
Georg Brandl116aa622007-08-15 14:28:22 +0000112.. data:: NSIG
113
114 One more than the number of the highest signal number.
115
Martin v. Löwis823725e2008-03-24 13:39:54 +0000116
Georg Brandl48310cd2009-01-03 21:18:54 +0000117.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000118
Georg Brandl18244152009-09-02 20:34:52 +0000119 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
120 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000121
122
Georg Brandl48310cd2009-01-03 21:18:54 +0000123.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000124
Georg Brandl48310cd2009-01-03 21:18:54 +0000125 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000126 SIGVTALRM upon expiration.
127
128
129.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000130
131 Decrements interval timer both when the process executes and when the
132 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
133 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000134 in user and kernel space. SIGPROF is delivered upon expiration.
135
136
Victor Stinnera9293352011-04-30 15:21:58 +0200137.. data:: SIG_BLOCK
138
139 A possible value for the *how* parameter to :func:`pthread_sigmask`
140 indicating that signals are to be blocked.
141
142 .. versionadded:: 3.3
143
144.. data:: SIG_UNBLOCK
145
146 A possible value for the *how* parameter to :func:`pthread_sigmask`
147 indicating that signals are to be unblocked.
148
149 .. versionadded:: 3.3
150
151.. data:: SIG_SETMASK
152
153 A possible value for the *how* parameter to :func:`pthread_sigmask`
154 indicating that the signal mask is to be replaced.
155
156 .. versionadded:: 3.3
157
158
Martin v. Löwis823725e2008-03-24 13:39:54 +0000159The :mod:`signal` module defines one exception:
160
161.. exception:: ItimerError
162
163 Raised to signal an error from the underlying :func:`setitimer` or
164 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000165 interval timer or a negative time is passed to :func:`setitimer`.
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200166 This error is a subtype of :exc:`OSError`.
167
168 .. versionadded:: 3.3
169 This error used to be a subtype of :exc:`IOError`, which is now an
170 alias of :exc:`OSError`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000171
172
Georg Brandl116aa622007-08-15 14:28:22 +0000173The :mod:`signal` module defines the following functions:
174
175
176.. function:: alarm(time)
177
178 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
179 sent to the process in *time* seconds. Any previously scheduled alarm is
180 canceled (only one alarm can be scheduled at any time). The returned value is
181 then the number of seconds before any previously set alarm was to have been
182 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
183 canceled. If the return value is zero, no alarm is currently scheduled. (See
184 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
185
186
187.. function:: getsignal(signalnum)
188
189 Return the current signal handler for the signal *signalnum*. The returned value
190 may be a callable Python object, or one of the special values
191 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
192 :const:`signal.SIG_IGN` means that the signal was previously ignored,
193 :const:`signal.SIG_DFL` means that the default way of handling the signal was
194 previously in use, and ``None`` means that the previous signal handler was not
195 installed from Python.
196
197
198.. function:: pause()
199
200 Cause the process to sleep until a signal is received; the appropriate handler
201 will then be called. Returns nothing. Not on Windows. (See the Unix man page
202 :manpage:`signal(2)`.)
203
Ross Lagerwallbc808222011-06-25 12:13:40 +0200204 See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and
205 :func:`sigpending`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200206
207
208.. function:: pthread_kill(thread_id, signum)
209
Antoine Pitrou682d4432012-03-31 21:09:00 +0200210 Send the signal *signum* to the thread *thread_id*, another thread in the
211 same process as the caller. The target thread can be executing any code
212 (Python or not). However, if the target thread is executing the Python
213 interpreter, the Python signal handlers will be :ref:`executed by the main
214 thread <signals-and-threads>`. Therefore, the only point of sending a signal to a particular
215 Python thread would be to force a running system call to fail with
216 :exc:`InterruptedError`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200217
Victor Stinner2a129742011-05-30 23:02:52 +0200218 Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
Antoine Pitrou682d4432012-03-31 21:09:00 +0200219 attribute of :class:`threading.Thread` objects to get a suitable value
220 for *thread_id*.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200221
222 If *signum* is 0, then no signal is sent, but error checking is still
Antoine Pitrou682d4432012-03-31 21:09:00 +0200223 performed; this can be used to check if the target thread is still running.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200224
225 Availability: Unix (see the man page :manpage:`pthread_kill(3)` for further
226 information).
227
228 See also :func:`os.kill`.
229
230 .. versionadded:: 3.3
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Victor Stinnera9293352011-04-30 15:21:58 +0200233.. function:: pthread_sigmask(how, mask)
234
235 Fetch and/or change the signal mask of the calling thread. The signal mask
236 is the set of signals whose delivery is currently blocked for the caller.
Victor Stinner35b300c2011-05-04 13:20:35 +0200237 Return the old signal mask as a set of signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200238
239 The behavior of the call is dependent on the value of *how*, as follows.
240
Antoine Pitrou8bbe9b42012-03-31 21:09:53 +0200241 * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
242 set and the *mask* argument.
243 * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
244 set of blocked signals. It is permissible to attempt to unblock a
245 signal which is not blocked.
246 * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
247 argument.
Victor Stinnera9293352011-04-30 15:21:58 +0200248
Victor Stinner35b300c2011-05-04 13:20:35 +0200249 *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
250 :const:`signal.SIGTERM`}). Use ``range(1, signal.NSIG)`` for a full mask
251 including all signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200252
253 For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
254 signal mask of the calling thread.
255
256 Availability: Unix. See the man page :manpage:`sigprocmask(3)` and
257 :manpage:`pthread_sigmask(3)` for further information.
258
Victor Stinnerb3e72192011-05-08 01:46:11 +0200259 See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
260
Victor Stinnera9293352011-04-30 15:21:58 +0200261 .. versionadded:: 3.3
262
263
Martin v. Löwis823725e2008-03-24 13:39:54 +0000264.. function:: setitimer(which, seconds[, interval])
265
Georg Brandl48310cd2009-01-03 21:18:54 +0000266 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000267 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000268 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000269 :func:`alarm`) and after that every *interval* seconds. The interval
270 timer specified by *which* can be cleared by setting seconds to zero.
271
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000272 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000273 The signal sent is dependent on the timer being used;
274 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000275 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
276 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
277
Martin v. Löwis823725e2008-03-24 13:39:54 +0000278 The old values are returned as a tuple: (delay, interval).
279
Georg Brandl495f7b52009-10-27 15:28:25 +0000280 Attempting to pass an invalid interval timer will cause an
281 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000282
Martin v. Löwis823725e2008-03-24 13:39:54 +0000283
284.. function:: getitimer(which)
285
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000286 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000287 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000288
Martin v. Löwis823725e2008-03-24 13:39:54 +0000289
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000290.. function:: set_wakeup_fd(fd)
291
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200292 Set the wakeup file descriptor to *fd*. When a signal is received, the
293 signal number is written as a single byte into the fd. This can be used by
294 a library to wakeup a poll or select call, allowing the signal to be fully
295 processed.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000296
297 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
298 library to remove any bytes before calling poll or select again.
299
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200300 Use for example ``struct.unpack('%uB' % len(data), data)`` to decode the
301 signal numbers list.
302
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000303 When threads are enabled, this function can only be called from the main thread;
304 attempting to call it from other threads will cause a :exc:`ValueError`
305 exception to be raised.
306
307
Christian Heimes8640e742008-02-23 16:23:06 +0000308.. function:: siginterrupt(signalnum, flag)
309
Georg Brandl18244152009-09-02 20:34:52 +0000310 Change system call restart behaviour: if *flag* is :const:`False`, system
311 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000312 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000313 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000314
Georg Brandl18244152009-09-02 20:34:52 +0000315 Note that installing a signal handler with :func:`signal` will reset the
316 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000317 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000318
Christian Heimes8640e742008-02-23 16:23:06 +0000319
Georg Brandl116aa622007-08-15 14:28:22 +0000320.. function:: signal(signalnum, handler)
321
322 Set the handler for signal *signalnum* to the function *handler*. *handler* can
323 be a callable Python object taking two arguments (see below), or one of the
324 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
325 signal handler will be returned (see the description of :func:`getsignal`
326 above). (See the Unix man page :manpage:`signal(2)`.)
327
328 When threads are enabled, this function can only be called from the main thread;
329 attempting to call it from other threads will cause a :exc:`ValueError`
330 exception to be raised.
331
332 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000333 stack frame (``None`` or a frame object; for a description of frame objects,
334 see the :ref:`description in the type hierarchy <frame-objects>` or see the
335 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Brian Curtinef9efbd2010-08-06 19:27:32 +0000337 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
338 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
339 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341
Victor Stinnerb3e72192011-05-08 01:46:11 +0200342.. function:: sigpending()
343
344 Examine the set of signals that are pending for delivery to the calling
345 thread (i.e., the signals which have been raised while blocked). Return the
346 set of the pending signals.
347
348 Availability: Unix (see the man page :manpage:`sigpending(2)` for further
349 information).
350
351 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
352
353 .. versionadded:: 3.3
354
355
356.. function:: sigwait(sigset)
357
358 Suspend execution of the calling thread until the delivery of one of the
359 signals specified in the signal set *sigset*. The function accepts the signal
360 (removes it from the pending list of signals), and returns the signal number.
361
362 Availability: Unix (see the man page :manpage:`sigwait(3)` for further
363 information).
364
Ross Lagerwallbc808222011-06-25 12:13:40 +0200365 See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`,
366 :func:`sigwaitinfo` and :func:`sigtimedwait`.
367
368 .. versionadded:: 3.3
369
370
371.. function:: sigwaitinfo(sigset)
372
373 Suspend execution of the calling thread until the delivery of one of the
374 signals specified in the signal set *sigset*. The function accepts the
375 signal and removes it from the pending list of signals. If one of the
376 signals in *sigset* is already pending for the calling thread, the function
377 will return immediately with information about that signal. The signal
378 handler is not called for the delivered signal. The function raises an
Antoine Pitrou767c0a82011-10-23 23:52:23 +0200379 :exc:`InterruptedError` if it is interrupted by a signal that is not in
380 *sigset*.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200381
382 The return value is an object representing the data contained in the
383 :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`,
384 :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`,
385 :attr:`si_band`.
386
387 Availability: Unix (see the man page :manpage:`sigwaitinfo(2)` for further
388 information).
389
390 See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`.
391
392 .. versionadded:: 3.3
393
394
Victor Stinner643cd682012-03-02 22:54:03 +0100395.. function:: sigtimedwait(sigset, timeout)
Ross Lagerwallbc808222011-06-25 12:13:40 +0200396
Victor Stinner643cd682012-03-02 22:54:03 +0100397 Like :func:`sigwaitinfo`, but takes an additional *timeout* argument
398 specifying a timeout. If *timeout* is specified as :const:`0`, a poll is
399 performed. Returns :const:`None` if a timeout occurs.
Ross Lagerwallbc808222011-06-25 12:13:40 +0200400
401 Availability: Unix (see the man page :manpage:`sigtimedwait(2)` for further
402 information).
403
404 See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200405
406 .. versionadded:: 3.3
407
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409.. _signal-example:
410
411Example
412-------
413
414Here is a minimal example program. It uses the :func:`alarm` function to limit
415the time spent waiting to open a file; this is useful if the file is for a
416serial device that may not be turned on, which would normally cause the
417:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
418before opening the file; if the operation takes too long, the alarm signal will
419be sent, and the handler raises an exception. ::
420
421 import signal, os
422
423 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000424 print('Signal handler called with signal', signum)
Antoine Pitrou4272d6a2011-10-12 19:10:10 +0200425 raise OSError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427 # Set the signal handler and a 5-second alarm
428 signal.signal(signal.SIGALRM, handler)
429 signal.alarm(5)
430
431 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000432 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434 signal.alarm(0) # Disable the alarm
435