blob: a3d562b4ffe78f3c697d418e25113006a3bcc6bc [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
Jean-Paul Calderone6ed7ac42010-06-19 19:58:37 +000016* There is no way to "block" signals temporarily from critical sections (since
17 this is not supported by all Unix flavors).
18
Georg Brandl116aa622007-08-15 14:28:22 +000019* Although Python signal handlers are called asynchronously as far as the Python
20 user is concerned, they can only occur between the "atomic" instructions of the
21 Python interpreter. This means that signals arriving during long calculations
22 implemented purely in C (such as regular expression matches on large bodies of
23 text) may be delayed for an arbitrary amount of time.
24
25* When a signal arrives during an I/O operation, it is possible that the I/O
26 operation raises an exception after the signal handler returns. This is
27 dependent on the underlying Unix system's semantics regarding interrupted system
28 calls.
29
30* Because the C signal handler always returns, it makes little sense to catch
31 synchronous errors like :const:`SIGFPE` or :const:`SIGSEGV`.
32
33* Python installs a small number of signal handlers by default: :const:`SIGPIPE`
34 is ignored (so write errors on pipes and sockets can be reported as ordinary
35 Python exceptions) and :const:`SIGINT` is translated into a
36 :exc:`KeyboardInterrupt` exception. All of these can be overridden.
37
38* Some care must be taken if both signals and threads are used in the same
39 program. The fundamental thing to remember in using signals and threads
40 simultaneously is: always perform :func:`signal` operations in the main thread
Georg Brandl48310cd2009-01-03 21:18:54 +000041 of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`,
42 :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
43 can set a new signal handler, and the main thread will be the only one to
44 receive signals (this is enforced by the Python :mod:`signal` module, even
45 if the underlying thread implementation supports sending signals to
46 individual threads). This means that signals can't be used as a means of
Martin v. Löwis823725e2008-03-24 13:39:54 +000047 inter-thread communication. Use locks instead.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49The variables defined in the :mod:`signal` module are:
50
51
52.. data:: SIG_DFL
53
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000054 This is one of two standard signal handling options; it will simply perform
55 the default function for the signal. For example, on most systems the
56 default action for :const:`SIGQUIT` is to dump core and exit, while the
57 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000058
59
60.. data:: SIG_IGN
61
62 This is another standard signal handler, which will simply ignore the given
63 signal.
64
65
66.. data:: SIG*
67
68 All the signal numbers are defined symbolically. For example, the hangup signal
69 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
70 names used in C programs, as found in ``<signal.h>``. The Unix man page for
71 ':cfunc:`signal`' lists the existing signals (on some systems this is
72 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
73 not all systems define the same set of signal names; only those names defined by
74 the system are defined by this module.
75
76
Brian Curtineb24d742010-04-12 17:16:38 +000077.. data:: CTRL_C_EVENT
78
Brian Curtinf045d772010-08-05 18:56:00 +000079 The signal corresponding to the CTRL+C keystroke event. This signal can
80 only be used with :func:`os.kill`.
81
Brian Curtineb24d742010-04-12 17:16:38 +000082 Availability: Windows.
83
Brian Curtin904bd392010-04-20 15:28:06 +000084 .. versionadded:: 3.2
85
Brian Curtineb24d742010-04-12 17:16:38 +000086
87.. data:: CTRL_BREAK_EVENT
88
Brian Curtinf045d772010-08-05 18:56:00 +000089 The signal corresponding to the CTRL+BREAK keystroke event. This signal can
90 only be used with :func:`os.kill`.
91
Brian Curtineb24d742010-04-12 17:16:38 +000092 Availability: Windows.
93
Brian Curtin904bd392010-04-20 15:28:06 +000094 .. versionadded:: 3.2
95
Brian Curtineb24d742010-04-12 17:16:38 +000096
Georg Brandl116aa622007-08-15 14:28:22 +000097.. data:: NSIG
98
99 One more than the number of the highest signal number.
100
Martin v. Löwis823725e2008-03-24 13:39:54 +0000101
Georg Brandl48310cd2009-01-03 21:18:54 +0000102.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000103
Georg Brandl18244152009-09-02 20:34:52 +0000104 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
105 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000106
107
Georg Brandl48310cd2009-01-03 21:18:54 +0000108.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000109
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000111 SIGVTALRM upon expiration.
112
113
114.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000115
116 Decrements interval timer both when the process executes and when the
117 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
118 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000119 in user and kernel space. SIGPROF is delivered upon expiration.
120
121
122The :mod:`signal` module defines one exception:
123
124.. exception:: ItimerError
125
126 Raised to signal an error from the underlying :func:`setitimer` or
127 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000128 interval timer or a negative time is passed to :func:`setitimer`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000129 This error is a subtype of :exc:`IOError`.
130
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132The :mod:`signal` module defines the following functions:
133
134
135.. function:: alarm(time)
136
137 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
138 sent to the process in *time* seconds. Any previously scheduled alarm is
139 canceled (only one alarm can be scheduled at any time). The returned value is
140 then the number of seconds before any previously set alarm was to have been
141 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
142 canceled. If the return value is zero, no alarm is currently scheduled. (See
143 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
144
145
146.. function:: getsignal(signalnum)
147
148 Return the current signal handler for the signal *signalnum*. The returned value
149 may be a callable Python object, or one of the special values
150 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
151 :const:`signal.SIG_IGN` means that the signal was previously ignored,
152 :const:`signal.SIG_DFL` means that the default way of handling the signal was
153 previously in use, and ``None`` means that the previous signal handler was not
154 installed from Python.
155
156
157.. function:: pause()
158
159 Cause the process to sleep until a signal is received; the appropriate handler
160 will then be called. Returns nothing. Not on Windows. (See the Unix man page
161 :manpage:`signal(2)`.)
162
163
Martin v. Löwis823725e2008-03-24 13:39:54 +0000164.. function:: setitimer(which, seconds[, interval])
165
Georg Brandl48310cd2009-01-03 21:18:54 +0000166 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000167 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000168 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000169 :func:`alarm`) and after that every *interval* seconds. The interval
170 timer specified by *which* can be cleared by setting seconds to zero.
171
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000172 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000173 The signal sent is dependent on the timer being used;
174 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000175 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
176 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
177
Martin v. Löwis823725e2008-03-24 13:39:54 +0000178 The old values are returned as a tuple: (delay, interval).
179
Georg Brandl495f7b52009-10-27 15:28:25 +0000180 Attempting to pass an invalid interval timer will cause an
181 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000182
Martin v. Löwis823725e2008-03-24 13:39:54 +0000183
184.. function:: getitimer(which)
185
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000186 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000187 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000188
Martin v. Löwis823725e2008-03-24 13:39:54 +0000189
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000190.. function:: set_wakeup_fd(fd)
191
192 Set the wakeup fd to *fd*. When a signal is received, a ``'\0'`` byte is
193 written to the fd. This can be used by a library to wakeup a poll or select
194 call, allowing the signal to be fully processed.
195
196 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
197 library to remove any bytes before calling poll or select again.
198
199 When threads are enabled, this function can only be called from the main thread;
200 attempting to call it from other threads will cause a :exc:`ValueError`
201 exception to be raised.
202
203
Christian Heimes8640e742008-02-23 16:23:06 +0000204.. function:: siginterrupt(signalnum, flag)
205
Georg Brandl18244152009-09-02 20:34:52 +0000206 Change system call restart behaviour: if *flag* is :const:`False`, system
207 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000208 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000209 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000210
Georg Brandl18244152009-09-02 20:34:52 +0000211 Note that installing a signal handler with :func:`signal` will reset the
212 restart behaviour to interruptible by implicitly calling
213 :cfunc:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000214
Christian Heimes8640e742008-02-23 16:23:06 +0000215
Georg Brandl116aa622007-08-15 14:28:22 +0000216.. function:: signal(signalnum, handler)
217
218 Set the handler for signal *signalnum* to the function *handler*. *handler* can
219 be a callable Python object taking two arguments (see below), or one of the
220 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
221 signal handler will be returned (see the description of :func:`getsignal`
222 above). (See the Unix man page :manpage:`signal(2)`.)
223
224 When threads are enabled, this function can only be called from the main thread;
225 attempting to call it from other threads will cause a :exc:`ValueError`
226 exception to be raised.
227
228 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000229 stack frame (``None`` or a frame object; for a description of frame objects,
230 see the :ref:`description in the type hierarchy <frame-objects>` or see the
231 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233
234.. _signal-example:
235
236Example
237-------
238
239Here is a minimal example program. It uses the :func:`alarm` function to limit
240the time spent waiting to open a file; this is useful if the file is for a
241serial device that may not be turned on, which would normally cause the
242:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
243before opening the file; if the operation takes too long, the alarm signal will
244be sent, and the handler raises an exception. ::
245
246 import signal, os
247
248 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000249 print('Signal handler called with signal', signum)
Collin Winterc79461b2007-09-01 23:34:30 +0000250 raise IOError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252 # Set the signal handler and a 5-second alarm
253 signal.signal(signal.SIGALRM, handler)
254 signal.alarm(5)
255
256 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000257 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259 signal.alarm(0) # Disable the alarm
260