blob: 29d56fcea51c049918657c1c4530ba721d082bc9 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`signal` --- Set handlers for asynchronous events
3======================================================
4
5.. module:: signal
6 :synopsis: Set handlers for asynchronous events.
7
8
9This module provides mechanisms to use signal handlers in Python. Some general
10rules for working with signals and their handlers:
11
12* A handler for a particular signal, once set, remains installed until it is
13 explicitly reset (Python emulates the BSD style interface regardless of the
14 underlying implementation), with the exception of the handler for
15 :const:`SIGCHLD`, which follows the underlying implementation.
16
17* There is no way to "block" signals temporarily from critical sections (since
18 this is not supported by all Unix flavors).
19
20* Although Python signal handlers are called asynchronously as far as the Python
21 user is concerned, they can only occur between the "atomic" instructions of the
22 Python interpreter. This means that signals arriving during long calculations
23 implemented purely in C (such as regular expression matches on large bodies of
24 text) may be delayed for an arbitrary amount of time.
25
26* When a signal arrives during an I/O operation, it is possible that the I/O
27 operation raises an exception after the signal handler returns. This is
28 dependent on the underlying Unix system's semantics regarding interrupted system
29 calls.
30
31* Because the C signal handler always returns, it makes little sense to catch
32 synchronous errors like :const:`SIGFPE` or :const:`SIGSEGV`.
33
34* Python installs a small number of signal handlers by default: :const:`SIGPIPE`
35 is ignored (so write errors on pipes and sockets can be reported as ordinary
36 Python exceptions) and :const:`SIGINT` is translated into a
37 :exc:`KeyboardInterrupt` exception. All of these can be overridden.
38
39* Some care must be taken if both signals and threads are used in the same
40 program. The fundamental thing to remember in using signals and threads
41 simultaneously is: always perform :func:`signal` operations in the main thread
Georg Brandlc62ef8b2009-01-03 20:55:06 +000042 of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`,
43 :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
44 can set a new signal handler, and the main thread will be the only one to
45 receive signals (this is enforced by the Python :mod:`signal` module, even
46 if the underlying thread implementation supports sending signals to
47 individual threads). This means that signals can't be used as a means of
Martin v. Löwisaef18b12008-03-24 13:31:16 +000048 inter-thread communication. Use locks instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +000049
50The variables defined in the :mod:`signal` module are:
51
52
53.. data:: SIG_DFL
54
Benjamin Petersondd5312d2008-12-19 02:28:56 +000055 This is one of two standard signal handling options; it will simply perform
56 the default function for the signal. For example, on most systems the
57 default action for :const:`SIGQUIT` is to dump core and exit, while the
58 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60
61.. data:: SIG_IGN
62
63 This is another standard signal handler, which will simply ignore the given
64 signal.
65
66
67.. data:: SIG*
68
69 All the signal numbers are defined symbolically. For example, the hangup signal
70 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
71 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Sandro Tosi98ed08f2012-01-14 16:42:02 +010072 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl8ec7f652007-08-15 14:28:01 +000073 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
74 not all systems define the same set of signal names; only those names defined by
75 the system are defined by this module.
76
77
Brian Curtine5aa8862010-04-02 23:26:06 +000078.. data:: CTRL_C_EVENT
79
Brian Curtin4d808892010-08-05 19:00:45 +000080 The signal corresponding to the CTRL+C keystroke event. This signal can
81 only be used with :func:`os.kill`.
82
Brian Curtine5aa8862010-04-02 23:26:06 +000083 Availability: Windows.
84
Brian Curtin1f8dd362010-04-20 15:23:18 +000085 .. versionadded:: 2.7
86
Brian Curtine5aa8862010-04-02 23:26:06 +000087
88.. data:: CTRL_BREAK_EVENT
89
Brian Curtin4d808892010-08-05 19:00:45 +000090 The signal corresponding to the CTRL+BREAK keystroke event. This signal can
91 only be used with :func:`os.kill`.
92
Brian Curtine5aa8862010-04-02 23:26:06 +000093 Availability: Windows.
94
Brian Curtin1f8dd362010-04-20 15:23:18 +000095 .. versionadded:: 2.7
96
Brian Curtine5aa8862010-04-02 23:26:06 +000097
Georg Brandl8ec7f652007-08-15 14:28:01 +000098.. data:: NSIG
99
100 One more than the number of the highest signal number.
101
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000102
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000103.. data:: ITIMER_REAL
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000104
Andrew M. Kuchling1f2af8c2008-04-05 02:47:07 +0000105 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration.
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000106
107
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000108.. data:: ITIMER_VIRTUAL
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000109
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000110 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000111 SIGVTALRM upon expiration.
112
113
114.. data:: ITIMER_PROF
Georg Brandlc62ef8b2009-01-03 20:55:06 +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öwisaef18b12008-03-24 13:31:16 +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 Brandlc62ef8b2009-01-03 20:55:06 +0000128 interval timer or a negative time is passed to :func:`setitimer`.
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000129 This error is a subtype of :exc:`IOError`.
130
131
Georg Brandl8ec7f652007-08-15 14:28:01 +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öwisaef18b12008-03-24 13:31:16 +0000164.. function:: setitimer(which, seconds[, interval])
165
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000166 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Andrew M. Kuchling9ff4aea2008-04-05 02:42:20 +0000167 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000168 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwisaef18b12008-03-24 13:31:16 +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
Andrew M. Kuchling1f2af8c2008-04-05 02:47:07 +0000172 When an interval timer fires, a signal is sent to the process.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000173 The signal sent is dependent on the timer being used;
174 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Andrew M. Kuchling1f2af8c2008-04-05 02:47:07 +0000175 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
176 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
177
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000178 The old values are returned as a tuple: (delay, interval).
179
Georg Brandl0968fd62009-10-22 07:05:48 +0000180 Attempting to pass an invalid interval timer will cause an
Georg Brandlc5026f82009-10-22 15:04:09 +0000181 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000182
183 .. versionadded:: 2.6
184
185
186.. function:: getitimer(which)
187
Andrew M. Kuchling1f2af8c2008-04-05 02:47:07 +0000188 Returns current value of a given interval timer specified by *which*.
Georg Brandlc5026f82009-10-22 15:04:09 +0000189 Availability: Unix.
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000190
191 .. versionadded:: 2.6
192
193
Guido van Rossum02de8972007-12-19 19:41:06 +0000194.. function:: set_wakeup_fd(fd)
195
196 Set the wakeup fd to *fd*. When a signal is received, a ``'\0'`` byte is
197 written to the fd. This can be used by a library to wakeup a poll or select
198 call, allowing the signal to be fully processed.
199
200 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
201 library to remove any bytes before calling poll or select again.
202
203 When threads are enabled, this function can only be called from the main thread;
204 attempting to call it from other threads will cause a :exc:`ValueError`
205 exception to be raised.
206
Victor Stinner059061a2011-04-18 16:34:31 +0200207 .. versionadded:: 2.6
208
Guido van Rossum02de8972007-12-19 19:41:06 +0000209
Facundo Batista7e251e82008-02-23 15:07:35 +0000210.. function:: siginterrupt(signalnum, flag)
211
Georg Brandlc5026f82009-10-22 15:04:09 +0000212 Change system call restart behaviour: if *flag* is :const:`False`, system
213 calls will be restarted when interrupted by signal *signalnum*, otherwise
214 system calls will be interrupted. Returns nothing. Availability: Unix (see
215 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000216
Georg Brandlc5026f82009-10-22 15:04:09 +0000217 Note that installing a signal handler with :func:`signal` will reset the
218 restart behaviour to interruptible by implicitly calling
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100219 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Facundo Batista7e251e82008-02-23 15:07:35 +0000220
221 .. versionadded:: 2.6
222
223
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224.. function:: signal(signalnum, handler)
225
226 Set the handler for signal *signalnum* to the function *handler*. *handler* can
227 be a callable Python object taking two arguments (see below), or one of the
228 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
229 signal handler will be returned (see the description of :func:`getsignal`
230 above). (See the Unix man page :manpage:`signal(2)`.)
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 The *handler* is called with two arguments: the signal number and the current
Georg Brandl86158fc2009-09-01 08:00:47 +0000237 stack frame (``None`` or a frame object; for a description of frame objects,
238 see the :ref:`description in the type hierarchy <frame-objects>` or see the
239 attribute descriptions in the :mod:`inspect` module).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240
Brian Curtin24af0e92010-08-06 19:41:01 +0000241 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
242 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
243 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
244
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
246.. _signal-example:
247
248Example
249-------
250
251Here is a minimal example program. It uses the :func:`alarm` function to limit
252the time spent waiting to open a file; this is useful if the file is for a
253serial device that may not be turned on, which would normally cause the
254:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
255before opening the file; if the operation takes too long, the alarm signal will
256be sent, and the handler raises an exception. ::
257
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000258 import signal, os
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260 def handler(signum, frame):
261 print 'Signal handler called with signal', signum
Georg Brandlc1edec32009-06-03 07:25:35 +0000262 raise IOError("Couldn't open device!")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000263
264 # Set the signal handler and a 5-second alarm
265 signal.signal(signal.SIGALRM, handler)
266 signal.alarm(5)
267
268 # This open() may hang indefinitely
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000269 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
271 signal.alarm(0) # Disable the alarm
272