blob: d3c498d7ed13ac908633bd48d8c1295d3d570dc2 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
42 of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, or
43 :func:`pause`; only the main thread can set a new signal handler, and the main
44 thread will be the only one to receive signals (this is enforced by the Python
45 :mod:`signal` module, even if the underlying thread implementation supports
46 sending signals to individual threads). This means that signals can't be used
47 as a means of inter-thread communication. Use locks instead.
48
49The variables defined in the :mod:`signal` module are:
50
51
52.. data:: SIG_DFL
53
54 This is one of two standard signal handling options; it will simply perform the
55 default function for the signal. For example, on most systems the default
56 action for :const:`SIGQUIT` is to dump core and exit, while the default action
57 for :const:`SIGCLD` is to simply ignore it.
58
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
77.. data:: NSIG
78
79 One more than the number of the highest signal number.
80
81The :mod:`signal` module defines the following functions:
82
83
84.. function:: alarm(time)
85
86 If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
87 sent to the process in *time* seconds. Any previously scheduled alarm is
88 canceled (only one alarm can be scheduled at any time). The returned value is
89 then the number of seconds before any previously set alarm was to have been
90 delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
91 canceled. If the return value is zero, no alarm is currently scheduled. (See
92 the Unix man page :manpage:`alarm(2)`.) Availability: Unix.
93
94
95.. function:: getsignal(signalnum)
96
97 Return the current signal handler for the signal *signalnum*. The returned value
98 may be a callable Python object, or one of the special values
99 :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here,
100 :const:`signal.SIG_IGN` means that the signal was previously ignored,
101 :const:`signal.SIG_DFL` means that the default way of handling the signal was
102 previously in use, and ``None`` means that the previous signal handler was not
103 installed from Python.
104
105
106.. function:: pause()
107
108 Cause the process to sleep until a signal is received; the appropriate handler
109 will then be called. Returns nothing. Not on Windows. (See the Unix man page
110 :manpage:`signal(2)`.)
111
112
113.. function:: signal(signalnum, handler)
114
115 Set the handler for signal *signalnum* to the function *handler*. *handler* can
116 be a callable Python object taking two arguments (see below), or one of the
117 special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous
118 signal handler will be returned (see the description of :func:`getsignal`
119 above). (See the Unix man page :manpage:`signal(2)`.)
120
121 When threads are enabled, this function can only be called from the main thread;
122 attempting to call it from other threads will cause a :exc:`ValueError`
123 exception to be raised.
124
125 The *handler* is called with two arguments: the signal number and the current
126 stack frame (``None`` or a frame object; for a description of frame objects, see
127 the reference manual section on the standard type hierarchy or see the attribute
128 descriptions in the :mod:`inspect` module).
129
130
131.. _signal-example:
132
133Example
134-------
135
136Here is a minimal example program. It uses the :func:`alarm` function to limit
137the time spent waiting to open a file; this is useful if the file is for a
138serial device that may not be turned on, which would normally cause the
139:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm
140before opening the file; if the operation takes too long, the alarm signal will
141be sent, and the handler raises an exception. ::
142
143 import signal, os
144
145 def handler(signum, frame):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000146 print('Signal handler called with signal', signum)
Collin Winterc79461b2007-09-01 23:34:30 +0000147 raise IOError("Couldn't open device!")
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 # Set the signal handler and a 5-second alarm
150 signal.signal(signal.SIGALRM, handler)
151 signal.alarm(5)
152
153 # This open() may hang indefinitely
154 fd = os.open('/dev/ttyS0', os.O_RDWR)
155
156 signal.alarm(0) # Disable the alarm
157