blob: 26d9320dee7292e34ede8e170c4608b8adb6231f [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
68 ':cfunc:`signal`' lists the existing signals (on some systems this is
69 :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
76 The signal corresponding to the CTRL+C keystroke event.
Brian Curtineb24d742010-04-12 17:16:38 +000077 Availability: Windows.
78
Brian Curtin904bd392010-04-20 15:28:06 +000079 .. versionadded:: 3.2
80
Brian Curtineb24d742010-04-12 17:16:38 +000081
82.. data:: CTRL_BREAK_EVENT
83
84 The signal corresponding to the CTRL+BREAK keystroke event.
Brian Curtineb24d742010-04-12 17:16:38 +000085 Availability: Windows.
86
Brian Curtin904bd392010-04-20 15:28:06 +000087 .. versionadded:: 3.2
88
Brian Curtineb24d742010-04-12 17:16:38 +000089
Georg Brandl116aa622007-08-15 14:28:22 +000090.. data:: NSIG
91
92 One more than the number of the highest signal number.
93
Martin v. Löwis823725e2008-03-24 13:39:54 +000094
Georg Brandl48310cd2009-01-03 21:18:54 +000095.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +000096
Georg Brandl18244152009-09-02 20:34:52 +000097 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
98 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +000099
100
Georg Brandl48310cd2009-01-03 21:18:54 +0000101.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000102
Georg Brandl48310cd2009-01-03 21:18:54 +0000103 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000104 SIGVTALRM upon expiration.
105
106
107.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000108
109 Decrements interval timer both when the process executes and when the
110 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
111 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000112 in user and kernel space. SIGPROF is delivered upon expiration.
113
114
Jean-Paul Calderone867c4352010-06-19 19:54:48 +0000115.. data:: SIG_BLOCK
116
117 A possible value for the *how* parameter to :func:`sigprocmask`
118 indicating that signals are to be blocked.
119
120 .. versionadded:: 2.7
121
122
123.. data:: SIG_UNBLOCK
124
125 A possible value for the *how* parameter to :func:`sigprocmask`
126 indicating that signals are to be unblocked.
127
128 .. versionadded:: 2.7
129
130
131.. data:: SIG_SETMASK
132
133 A possible value for the *how* parameter to :func:`sigprocmask`
134 indicating that the signal mask is to be replaced.
135
136 .. versionadded:: 2.7
137
138
139.. data:: SFD_CLOEXEC
140
141 A possible flag in the *flags* parameter to :func:`signalfd` which causes
142 the new file descriptor to be marked as close-on-exec.
143
144 .. versionadded:: 2.7
145
146
147.. data:: SFD_NONBLOCK
148
149 A possible flag in the *flags* parameter to :func:`signalfd` which causes
150 the new file description to be set non-blocking.
151
152 .. versionadded:: 2.7
153
154
Martin v. Löwis823725e2008-03-24 13:39:54 +0000155The :mod:`signal` module defines one exception:
156
157.. exception:: ItimerError
158
159 Raised to signal an error from the underlying :func:`setitimer` or
160 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000161 interval timer or a negative time is passed to :func:`setitimer`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000162 This error is a subtype of :exc:`IOError`.
163
164
Georg Brandl116aa622007-08-15 14:28:22 +0000165The :mod:`signal` module defines the following functions:
166
167
168.. function:: alarm(time)
169
170 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
171 sent to the process in *time* seconds. Any previously scheduled alarm is
172 canceled (only one alarm can be scheduled at any time). The returned value is
173 then the number of seconds before any previously set alarm was to have been
174 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
175 canceled. If the return value is zero, no alarm is currently scheduled. (See
176 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
177
178
179.. function:: getsignal(signalnum)
180
181 Return the current signal handler for the signal *signalnum*. The returned value
182 may be a callable Python object, or one of the special values
183 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
184 :const:`signal.SIG_IGN` means that the signal was previously ignored,
185 :const:`signal.SIG_DFL` means that the default way of handling the signal was
186 previously in use, and ``None`` means that the previous signal handler was not
187 installed from Python.
188
189
190.. function:: pause()
191
192 Cause the process to sleep until a signal is received; the appropriate handler
193 will then be called. Returns nothing. Not on Windows. (See the Unix man page
194 :manpage:`signal(2)`.)
195
196
Martin v. Löwis823725e2008-03-24 13:39:54 +0000197.. function:: setitimer(which, seconds[, interval])
198
Georg Brandl48310cd2009-01-03 21:18:54 +0000199 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000200 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000201 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000202 :func:`alarm`) and after that every *interval* seconds. The interval
203 timer specified by *which* can be cleared by setting seconds to zero.
204
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000205 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000206 The signal sent is dependent on the timer being used;
207 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000208 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
209 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
210
Martin v. Löwis823725e2008-03-24 13:39:54 +0000211 The old values are returned as a tuple: (delay, interval).
212
Georg Brandl495f7b52009-10-27 15:28:25 +0000213 Attempting to pass an invalid interval timer will cause an
214 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000215
Martin v. Löwis823725e2008-03-24 13:39:54 +0000216
217.. function:: getitimer(which)
218
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000219 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000220 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000221
Martin v. Löwis823725e2008-03-24 13:39:54 +0000222
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000223.. function:: set_wakeup_fd(fd)
224
225 Set the wakeup fd to *fd*. When a signal is received, a ``'\0'`` byte is
226 written to the fd. This can be used by a library to wakeup a poll or select
227 call, allowing the signal to be fully processed.
228
229 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
230 library to remove any bytes before calling poll or select again.
231
232 When threads are enabled, this function can only be called from the main thread;
233 attempting to call it from other threads will cause a :exc:`ValueError`
234 exception to be raised.
235
236
Christian Heimes8640e742008-02-23 16:23:06 +0000237.. function:: siginterrupt(signalnum, flag)
238
Georg Brandl18244152009-09-02 20:34:52 +0000239 Change system call restart behaviour: if *flag* is :const:`False`, system
240 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000241 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000242 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000243
Georg Brandl18244152009-09-02 20:34:52 +0000244 Note that installing a signal handler with :func:`signal` will reset the
245 restart behaviour to interruptible by implicitly calling
246 :cfunc:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000247
Christian Heimes8640e742008-02-23 16:23:06 +0000248
Georg Brandl116aa622007-08-15 14:28:22 +0000249.. function:: signal(signalnum, handler)
250
251 Set the handler for signal *signalnum* to the function *handler*. *handler* can
252 be a callable Python object taking two arguments (see below), or one of the
253 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
254 signal handler will be returned (see the description of :func:`getsignal`
255 above). (See the Unix man page :manpage:`signal(2)`.)
256
257 When threads are enabled, this function can only be called from the main thread;
258 attempting to call it from other threads will cause a :exc:`ValueError`
259 exception to be raised.
260
261 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000262 stack frame (``None`` or a frame object; for a description of frame objects,
263 see the :ref:`description in the type hierarchy <frame-objects>` or see the
264 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
Jean-Paul Calderone867c4352010-06-19 19:54:48 +0000267.. function:: signalfd(fd, mask[, flags])
268
269 Create a new file descriptor on which to receive signals or modify the
270 mask of such a file descriptor previously created by this function.
271 Availability: Linux (See the manpage :manpage:`signalfd(2)` for further
272 information).
273
274 If *fd* is ``-1``, a new file descriptor will be created. Otherwise,
275 *fd* must be a file descriptor previously returned by this function.
276
277 *mask* is a list of signal numbers which will trigger data on this file
278 descriptor.
279
280 *flags* is a bit mask which may include any :const:`signal.SFD_*` flag.
281
282 .. versionadded:: 2.7
283
284
285.. function:: sigprocmask(how, mask)
286
287 Set the signal mask for the process. The old signal mask is returned.
288 Availability: Unix (See the Unix man page :manpage:`sigprocmask(2)` and
289 :manpage:`pthread_sigmask(2)`.)
290
291 If *how* is :const:`signal.SIG_BLOCK`, the signals in the mask are added
292 to the set of blocked signals.
293
294 If *how* is :const:`signal.SIG_UNBLOCK`, the signals in the mask are
295 removed from the set of blocked signals.
296
297 If *how* is :const:`signal.SIG_SETMASK`, the signals in the mask are set
298 as blocked and the signals not in the mask are set as unblocked.
299
300 *mask* is a list of signal numbers (eg :const:`signal.SIGUSR1`).
301
302 .. versionadded:: 2.7
303
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305.. _signal-example:
306
307Example
308-------
309
310Here is a minimal example program. It uses the :func:`alarm` function to limit
311the time spent waiting to open a file; this is useful if the file is for a
312serial device that may not be turned on, which would normally cause the
313:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
314before opening the file; if the operation takes too long, the alarm signal will
315be sent, and the handler raises an exception. ::
316
317 import signal, os
318
319 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000320 print('Signal handler called with signal', signum)
Collin Winterc79461b2007-09-01 23:34:30 +0000321 raise IOError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323 # Set the signal handler and a 5-second alarm
324 signal.signal(signal.SIGALRM, handler)
325 signal.alarm(5)
326
327 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000328 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330 signal.alarm(0) # Disable the alarm
331