blob: f2a37cc65a666bf9c4da4d7b6ce56fafa4347b50 [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
8This module provides mechanisms to use signal handlers in Python. Some general
9rules for working with signals and their handlers:
10
11* A handler for a particular signal, once set, remains installed until it is
12 explicitly reset (Python emulates the BSD style interface regardless of the
13 underlying implementation), with the exception of the handler for
14 :const:`SIGCHLD`, which follows the underlying implementation.
15
Georg Brandl116aa622007-08-15 14:28:22 +000016* Although Python signal handlers are called asynchronously as far as the Python
17 user is concerned, they can only occur between the "atomic" instructions of the
18 Python interpreter. This means that signals arriving during long calculations
19 implemented purely in C (such as regular expression matches on large bodies of
20 text) may be delayed for an arbitrary amount of time.
21
22* When a signal arrives during an I/O operation, it is possible that the I/O
23 operation raises an exception after the signal handler returns. This is
24 dependent on the underlying Unix system's semantics regarding interrupted system
25 calls.
26
27* Because the C signal handler always returns, it makes little sense to catch
28 synchronous errors like :const:`SIGFPE` or :const:`SIGSEGV`.
29
30* Python installs a small number of signal handlers by default: :const:`SIGPIPE`
31 is ignored (so write errors on pipes and sockets can be reported as ordinary
32 Python exceptions) and :const:`SIGINT` is translated into a
33 :exc:`KeyboardInterrupt` exception. All of these can be overridden.
34
35* Some care must be taken if both signals and threads are used in the same
36 program. The fundamental thing to remember in using signals and threads
37 simultaneously is: always perform :func:`signal` operations in the main thread
Georg Brandl48310cd2009-01-03 21:18:54 +000038 of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`,
39 :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
40 can set a new signal handler, and the main thread will be the only one to
41 receive signals (this is enforced by the Python :mod:`signal` module, even
42 if the underlying thread implementation supports sending signals to
43 individual threads). This means that signals can't be used as a means of
Martin v. Löwis823725e2008-03-24 13:39:54 +000044 inter-thread communication. Use locks instead.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46The variables defined in the :mod:`signal` module are:
47
48
49.. data:: SIG_DFL
50
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000051 This is one of two standard signal handling options; it will simply perform
52 the default function for the signal. For example, on most systems the
53 default action for :const:`SIGQUIT` is to dump core and exit, while the
54 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000055
56
57.. data:: SIG_IGN
58
59 This is another standard signal handler, which will simply ignore the given
60 signal.
61
62
63.. data:: SIG*
64
65 All the signal numbers are defined symbolically. For example, the hangup signal
66 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
67 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Georg Brandl60203b42010-10-06 10:11:56 +000068 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +000069 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
70 not all systems define the same set of signal names; only those names defined by
71 the system are defined by this module.
72
73
Brian Curtineb24d742010-04-12 17:16:38 +000074.. data:: CTRL_C_EVENT
75
Brian Curtinf045d772010-08-05 18:56:00 +000076 The signal corresponding to the CTRL+C keystroke event. This signal can
77 only be used with :func:`os.kill`.
78
Brian Curtineb24d742010-04-12 17:16:38 +000079 Availability: Windows.
80
Brian Curtin904bd392010-04-20 15:28:06 +000081 .. versionadded:: 3.2
82
Brian Curtineb24d742010-04-12 17:16:38 +000083
84.. data:: CTRL_BREAK_EVENT
85
Brian Curtinf045d772010-08-05 18:56:00 +000086 The signal corresponding to the CTRL+BREAK keystroke event. This signal can
87 only be used with :func:`os.kill`.
88
Brian Curtineb24d742010-04-12 17:16:38 +000089 Availability: Windows.
90
Brian Curtin904bd392010-04-20 15:28:06 +000091 .. versionadded:: 3.2
92
Brian Curtineb24d742010-04-12 17:16:38 +000093
Georg Brandl116aa622007-08-15 14:28:22 +000094.. data:: NSIG
95
96 One more than the number of the highest signal number.
97
Martin v. Löwis823725e2008-03-24 13:39:54 +000098
Georg Brandl48310cd2009-01-03 21:18:54 +000099.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000100
Georg Brandl18244152009-09-02 20:34:52 +0000101 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
102 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000103
104
Georg Brandl48310cd2009-01-03 21:18:54 +0000105.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000106
Georg Brandl48310cd2009-01-03 21:18:54 +0000107 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000108 SIGVTALRM upon expiration.
109
110
111.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000112
113 Decrements interval timer both when the process executes and when the
114 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
115 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000116 in user and kernel space. SIGPROF is delivered upon expiration.
117
118
Victor Stinnera9293352011-04-30 15:21:58 +0200119.. data:: SIG_BLOCK
120
121 A possible value for the *how* parameter to :func:`pthread_sigmask`
122 indicating that signals are to be blocked.
123
124 .. versionadded:: 3.3
125
126.. data:: SIG_UNBLOCK
127
128 A possible value for the *how* parameter to :func:`pthread_sigmask`
129 indicating that signals are to be unblocked.
130
131 .. versionadded:: 3.3
132
133.. data:: SIG_SETMASK
134
135 A possible value for the *how* parameter to :func:`pthread_sigmask`
136 indicating that the signal mask is to be replaced.
137
138 .. versionadded:: 3.3
139
140
Martin v. Löwis823725e2008-03-24 13:39:54 +0000141The :mod:`signal` module defines one exception:
142
143.. exception:: ItimerError
144
145 Raised to signal an error from the underlying :func:`setitimer` or
146 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000147 interval timer or a negative time is passed to :func:`setitimer`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000148 This error is a subtype of :exc:`IOError`.
149
150
Georg Brandl116aa622007-08-15 14:28:22 +0000151The :mod:`signal` module defines the following functions:
152
153
154.. function:: alarm(time)
155
156 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
157 sent to the process in *time* seconds. Any previously scheduled alarm is
158 canceled (only one alarm can be scheduled at any time). The returned value is
159 then the number of seconds before any previously set alarm was to have been
160 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
161 canceled. If the return value is zero, no alarm is currently scheduled. (See
162 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
163
164
165.. function:: getsignal(signalnum)
166
167 Return the current signal handler for the signal *signalnum*. The returned value
168 may be a callable Python object, or one of the special values
169 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
170 :const:`signal.SIG_IGN` means that the signal was previously ignored,
171 :const:`signal.SIG_DFL` means that the default way of handling the signal was
172 previously in use, and ``None`` means that the previous signal handler was not
173 installed from Python.
174
175
176.. function:: pause()
177
178 Cause the process to sleep until a signal is received; the appropriate handler
179 will then be called. Returns nothing. Not on Windows. (See the Unix man page
180 :manpage:`signal(2)`.)
181
Victor Stinnerb3e72192011-05-08 01:46:11 +0200182 See also :func:`sigwait` and :func:`sigpending`.
183
184
185.. function:: pthread_kill(thread_id, signum)
186
187 Send the signal *signum* to the thread *thread_id*, another thread in the same
188 process as the caller. The signal is asynchronously directed to thread.
189
Victor Stinner2a129742011-05-30 23:02:52 +0200190 Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident`
191 attribute of :attr:`threading.Thread` to get a 'thread identifier' for
192 *thread_id*.
Victor Stinnerb3e72192011-05-08 01:46:11 +0200193
194 If *signum* is 0, then no signal is sent, but error checking is still
195 performed; this can be used to check if a thread is still running.
196
197 Availability: Unix (see the man page :manpage:`pthread_kill(3)` for further
198 information).
199
200 See also :func:`os.kill`.
201
202 .. versionadded:: 3.3
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Victor Stinnera9293352011-04-30 15:21:58 +0200205.. function:: pthread_sigmask(how, mask)
206
207 Fetch and/or change the signal mask of the calling thread. The signal mask
208 is the set of signals whose delivery is currently blocked for the caller.
Victor Stinner35b300c2011-05-04 13:20:35 +0200209 Return the old signal mask as a set of signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200210
211 The behavior of the call is dependent on the value of *how*, as follows.
212
213 * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current
214 set and the *mask* argument.
215 * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current
216 set of blocked signals. It is permissible to attempt to unblock a
217 signal which is not blocked.
218 * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask*
219 argument.
220
Victor Stinner35b300c2011-05-04 13:20:35 +0200221 *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`,
222 :const:`signal.SIGTERM`}). Use ``range(1, signal.NSIG)`` for a full mask
223 including all signals.
Victor Stinnera9293352011-04-30 15:21:58 +0200224
225 For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
226 signal mask of the calling thread.
227
228 Availability: Unix. See the man page :manpage:`sigprocmask(3)` and
229 :manpage:`pthread_sigmask(3)` for further information.
230
Victor Stinnerb3e72192011-05-08 01:46:11 +0200231 See also :func:`pause`, :func:`sigpending` and :func:`sigwait`.
232
Victor Stinnera9293352011-04-30 15:21:58 +0200233 .. versionadded:: 3.3
234
235
Martin v. Löwis823725e2008-03-24 13:39:54 +0000236.. function:: setitimer(which, seconds[, interval])
237
Georg Brandl48310cd2009-01-03 21:18:54 +0000238 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000239 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000240 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000241 :func:`alarm`) and after that every *interval* seconds. The interval
242 timer specified by *which* can be cleared by setting seconds to zero.
243
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000244 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000245 The signal sent is dependent on the timer being used;
246 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000247 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
248 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
249
Martin v. Löwis823725e2008-03-24 13:39:54 +0000250 The old values are returned as a tuple: (delay, interval).
251
Georg Brandl495f7b52009-10-27 15:28:25 +0000252 Attempting to pass an invalid interval timer will cause an
253 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000254
Martin v. Löwis823725e2008-03-24 13:39:54 +0000255
256.. function:: getitimer(which)
257
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000258 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000259 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000260
Martin v. Löwis823725e2008-03-24 13:39:54 +0000261
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000262.. function:: set_wakeup_fd(fd)
263
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200264 Set the wakeup file descriptor to *fd*. When a signal is received, the
265 signal number is written as a single byte into the fd. This can be used by
266 a library to wakeup a poll or select call, allowing the signal to be fully
267 processed.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000268
269 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
270 library to remove any bytes before calling poll or select again.
271
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200272 Use for example ``struct.unpack('%uB' % len(data), data)`` to decode the
273 signal numbers list.
274
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000275 When threads are enabled, this function can only be called from the main thread;
276 attempting to call it from other threads will cause a :exc:`ValueError`
277 exception to be raised.
278
279
Christian Heimes8640e742008-02-23 16:23:06 +0000280.. function:: siginterrupt(signalnum, flag)
281
Georg Brandl18244152009-09-02 20:34:52 +0000282 Change system call restart behaviour: if *flag* is :const:`False`, system
283 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000284 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000285 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000286
Georg Brandl18244152009-09-02 20:34:52 +0000287 Note that installing a signal handler with :func:`signal` will reset the
288 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000289 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000290
Christian Heimes8640e742008-02-23 16:23:06 +0000291
Georg Brandl116aa622007-08-15 14:28:22 +0000292.. function:: signal(signalnum, handler)
293
294 Set the handler for signal *signalnum* to the function *handler*. *handler* can
295 be a callable Python object taking two arguments (see below), or one of the
296 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
297 signal handler will be returned (see the description of :func:`getsignal`
298 above). (See the Unix man page :manpage:`signal(2)`.)
299
300 When threads are enabled, this function can only be called from the main thread;
301 attempting to call it from other threads will cause a :exc:`ValueError`
302 exception to be raised.
303
304 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000305 stack frame (``None`` or a frame object; for a description of frame objects,
306 see the :ref:`description in the type hierarchy <frame-objects>` or see the
307 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Brian Curtinef9efbd2010-08-06 19:27:32 +0000309 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
310 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
311 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Victor Stinnerb3e72192011-05-08 01:46:11 +0200314.. function:: sigpending()
315
316 Examine the set of signals that are pending for delivery to the calling
317 thread (i.e., the signals which have been raised while blocked). Return the
318 set of the pending signals.
319
320 Availability: Unix (see the man page :manpage:`sigpending(2)` for further
321 information).
322
323 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`.
324
325 .. versionadded:: 3.3
326
327
328.. function:: sigwait(sigset)
329
330 Suspend execution of the calling thread until the delivery of one of the
331 signals specified in the signal set *sigset*. The function accepts the signal
332 (removes it from the pending list of signals), and returns the signal number.
333
334 Availability: Unix (see the man page :manpage:`sigwait(3)` for further
335 information).
336
337 See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigpending`.
338
339 .. versionadded:: 3.3
340
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342.. _signal-example:
343
344Example
345-------
346
347Here is a minimal example program. It uses the :func:`alarm` function to limit
348the time spent waiting to open a file; this is useful if the file is for a
349serial device that may not be turned on, which would normally cause the
350:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
351before opening the file; if the operation takes too long, the alarm signal will
352be sent, and the handler raises an exception. ::
353
354 import signal, os
355
356 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000357 print('Signal handler called with signal', signum)
Collin Winterc79461b2007-09-01 23:34:30 +0000358 raise IOError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360 # Set the signal handler and a 5-second alarm
361 signal.signal(signal.SIGALRM, handler)
362 signal.alarm(5)
363
364 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000365 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367 signal.alarm(0) # Disable the alarm
368