blob: d1cae13d62e61fb7c9a20be9e54518747375f959 [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-------------
Jean-Paul Calderone6ed7ac42010-06-19 19:58:37 +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
47Signals and threads
48^^^^^^^^^^^^^^^^^^^
49
50Python signal handlers are always executed in the main Python thread,
51even if the signal was received in another thread. This means that signals
52can't be used as a means of inter-thread communication. You can use
53the synchronization primitives from the :mod:`threading` module instead.
54
55Besides, only the main thread is allowed to set a new signal handler.
56
57
58Module contents
59---------------
Georg Brandl116aa622007-08-15 14:28:22 +000060
61The variables defined in the :mod:`signal` module are:
62
63
64.. data:: SIG_DFL
65
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000066 This is one of two standard signal handling options; it will simply perform
67 the default function for the signal. For example, on most systems the
68 default action for :const:`SIGQUIT` is to dump core and exit, while the
69 default action for :const:`SIGCHLD` is to simply ignore it.
Georg Brandl116aa622007-08-15 14:28:22 +000070
71
72.. data:: SIG_IGN
73
74 This is another standard signal handler, which will simply ignore the given
75 signal.
76
77
78.. data:: SIG*
79
80 All the signal numbers are defined symbolically. For example, the hangup signal
81 is defined as :const:`signal.SIGHUP`; the variable names are identical to the
82 names used in C programs, as found in ``<signal.h>``. The Unix man page for
Georg Brandl60203b42010-10-06 10:11:56 +000083 ':c:func:`signal`' lists the existing signals (on some systems this is
Georg Brandl116aa622007-08-15 14:28:22 +000084 :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
85 not all systems define the same set of signal names; only those names defined by
86 the system are defined by this module.
87
88
Brian Curtineb24d742010-04-12 17:16:38 +000089.. data:: CTRL_C_EVENT
90
Brian Curtinf045d772010-08-05 18:56:00 +000091 The signal corresponding to the CTRL+C keystroke event. This signal can
92 only be used with :func:`os.kill`.
93
Brian Curtineb24d742010-04-12 17:16:38 +000094 Availability: Windows.
95
Brian Curtin904bd392010-04-20 15:28:06 +000096 .. versionadded:: 3.2
97
Brian Curtineb24d742010-04-12 17:16:38 +000098
99.. data:: CTRL_BREAK_EVENT
100
Brian Curtinf045d772010-08-05 18:56:00 +0000101 The signal corresponding to the CTRL+BREAK keystroke event. This signal can
102 only be used with :func:`os.kill`.
103
Brian Curtineb24d742010-04-12 17:16:38 +0000104 Availability: Windows.
105
Brian Curtin904bd392010-04-20 15:28:06 +0000106 .. versionadded:: 3.2
107
Brian Curtineb24d742010-04-12 17:16:38 +0000108
Georg Brandl116aa622007-08-15 14:28:22 +0000109.. data:: NSIG
110
111 One more than the number of the highest signal number.
112
Martin v. Löwis823725e2008-03-24 13:39:54 +0000113
Georg Brandl48310cd2009-01-03 21:18:54 +0000114.. data:: ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000115
Georg Brandl18244152009-09-02 20:34:52 +0000116 Decrements interval timer in real time, and delivers :const:`SIGALRM` upon
117 expiration.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000118
119
Georg Brandl48310cd2009-01-03 21:18:54 +0000120.. data:: ITIMER_VIRTUAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000121
Georg Brandl48310cd2009-01-03 21:18:54 +0000122 Decrements interval timer only when the process is executing, and delivers
Martin v. Löwis823725e2008-03-24 13:39:54 +0000123 SIGVTALRM upon expiration.
124
125
126.. data:: ITIMER_PROF
Georg Brandl48310cd2009-01-03 21:18:54 +0000127
128 Decrements interval timer both when the process executes and when the
129 system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
130 this timer is usually used to profile the time spent by the application
Martin v. Löwis823725e2008-03-24 13:39:54 +0000131 in user and kernel space. SIGPROF is delivered upon expiration.
132
133
134The :mod:`signal` module defines one exception:
135
136.. exception:: ItimerError
137
138 Raised to signal an error from the underlying :func:`setitimer` or
139 :func:`getitimer` implementation. Expect this error if an invalid
Georg Brandl48310cd2009-01-03 21:18:54 +0000140 interval timer or a negative time is passed to :func:`setitimer`.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000141 This error is a subtype of :exc:`IOError`.
142
143
Georg Brandl116aa622007-08-15 14:28:22 +0000144The :mod:`signal` module defines the following functions:
145
146
147.. function:: alarm(time)
148
149 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
150 sent to the process in *time* seconds. Any previously scheduled alarm is
151 canceled (only one alarm can be scheduled at any time). The returned value is
152 then the number of seconds before any previously set alarm was to have been
153 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
154 canceled. If the return value is zero, no alarm is currently scheduled. (See
155 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
156
157
158.. function:: getsignal(signalnum)
159
160 Return the current signal handler for the signal *signalnum*. The returned value
161 may be a callable Python object, or one of the special values
162 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
163 :const:`signal.SIG_IGN` means that the signal was previously ignored,
164 :const:`signal.SIG_DFL` means that the default way of handling the signal was
165 previously in use, and ``None`` means that the previous signal handler was not
166 installed from Python.
167
168
169.. function:: pause()
170
171 Cause the process to sleep until a signal is received; the appropriate handler
172 will then be called. Returns nothing. Not on Windows. (See the Unix man page
173 :manpage:`signal(2)`.)
174
175
Martin v. Löwis823725e2008-03-24 13:39:54 +0000176.. function:: setitimer(which, seconds[, interval])
177
Georg Brandl48310cd2009-01-03 21:18:54 +0000178 Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000179 :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
Georg Brandl48310cd2009-01-03 21:18:54 +0000180 by *which* to fire after *seconds* (float is accepted, different from
Martin v. Löwis823725e2008-03-24 13:39:54 +0000181 :func:`alarm`) and after that every *interval* seconds. The interval
182 timer specified by *which* can be cleared by setting seconds to zero.
183
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000184 When an interval timer fires, a signal is sent to the process.
Georg Brandl48310cd2009-01-03 21:18:54 +0000185 The signal sent is dependent on the timer being used;
186 :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000187 :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
188 and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
189
Martin v. Löwis823725e2008-03-24 13:39:54 +0000190 The old values are returned as a tuple: (delay, interval).
191
Georg Brandl495f7b52009-10-27 15:28:25 +0000192 Attempting to pass an invalid interval timer will cause an
193 :exc:`ItimerError`. Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000194
Martin v. Löwis823725e2008-03-24 13:39:54 +0000195
196.. function:: getitimer(which)
197
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000198 Returns current value of a given interval timer specified by *which*.
Georg Brandl495f7b52009-10-27 15:28:25 +0000199 Availability: Unix.
Martin v. Löwis823725e2008-03-24 13:39:54 +0000200
Martin v. Löwis823725e2008-03-24 13:39:54 +0000201
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000202.. function:: set_wakeup_fd(fd)
203
204 Set the wakeup fd to *fd*. When a signal is received, a ``'\0'`` byte is
205 written to the fd. This can be used by a library to wakeup a poll or select
206 call, allowing the signal to be fully processed.
207
208 The old wakeup fd is returned. *fd* must be non-blocking. It is up to the
209 library to remove any bytes before calling poll or select again.
210
211 When threads are enabled, this function can only be called from the main thread;
212 attempting to call it from other threads will cause a :exc:`ValueError`
213 exception to be raised.
214
215
Christian Heimes8640e742008-02-23 16:23:06 +0000216.. function:: siginterrupt(signalnum, flag)
217
Georg Brandl18244152009-09-02 20:34:52 +0000218 Change system call restart behaviour: if *flag* is :const:`False`, system
219 calls will be restarted when interrupted by signal *signalnum*, otherwise
Georg Brandl495f7b52009-10-27 15:28:25 +0000220 system calls will be interrupted. Returns nothing. Availability: Unix (see
Georg Brandl18244152009-09-02 20:34:52 +0000221 the man page :manpage:`siginterrupt(3)` for further information).
Georg Brandl48310cd2009-01-03 21:18:54 +0000222
Georg Brandl18244152009-09-02 20:34:52 +0000223 Note that installing a signal handler with :func:`signal` will reset the
224 restart behaviour to interruptible by implicitly calling
Georg Brandl60203b42010-10-06 10:11:56 +0000225 :c:func:`siginterrupt` with a true *flag* value for the given signal.
Christian Heimes8640e742008-02-23 16:23:06 +0000226
Christian Heimes8640e742008-02-23 16:23:06 +0000227
Georg Brandl116aa622007-08-15 14:28:22 +0000228.. function:: signal(signalnum, handler)
229
230 Set the handler for signal *signalnum* to the function *handler*. *handler* can
231 be a callable Python object taking two arguments (see below), or one of the
232 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
233 signal handler will be returned (see the description of :func:`getsignal`
234 above). (See the Unix man page :manpage:`signal(2)`.)
235
236 When threads are enabled, this function can only be called from the main thread;
237 attempting to call it from other threads will cause a :exc:`ValueError`
238 exception to be raised.
239
240 The *handler* is called with two arguments: the signal number and the current
Georg Brandla6053b42009-09-01 08:11:14 +0000241 stack frame (``None`` or a frame object; for a description of frame objects,
242 see the :ref:`description in the type hierarchy <frame-objects>` or see the
243 attribute descriptions in the :mod:`inspect` module).
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Brian Curtinef9efbd2010-08-06 19:27:32 +0000245 On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
246 :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
247 :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
248
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250.. _signal-example:
251
252Example
253-------
254
255Here is a minimal example program. It uses the :func:`alarm` function to limit
256the time spent waiting to open a file; this is useful if the file is for a
257serial device that may not be turned on, which would normally cause the
258:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
259before opening the file; if the operation takes too long, the alarm signal will
260be sent, and the handler raises an exception. ::
261
262 import signal, os
263
264 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000265 print('Signal handler called with signal', signum)
Collin Winterc79461b2007-09-01 23:34:30 +0000266 raise IOError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268 # Set the signal handler and a 5-second alarm
269 signal.signal(signal.SIGALRM, handler)
270 signal.alarm(5)
271
272 # This open() may hang indefinitely
Georg Brandl48310cd2009-01-03 21:18:54 +0000273 fd = os.open('/dev/ttyS0', os.O_RDWR)
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275 signal.alarm(0) # Disable the alarm
276