Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 42db27f

Browse files
committed
Added an example that uses signal.alarm() to time out an os.open() that
takes too long. This example relies on the fact that raising an exception in a signal handler causes the exception to be re-raised when the main line of the program resumes execution. Is this guaranteed in CPython, or is this something that just happens to work by accident? Also fixed a typo.
1 parent ce4ba89 commit 42db27f

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

Doc/lib/libsignal.tex

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ \section{\module{signal} ---
66
\modulesynopsis{Set handlers for asynchronous events.}
77

88
This module provides mechanisms to use signal handlers in Python.
9-
Some general rules for working with signals handlers:
9+
Some general rules for working with signals and their handlers:
1010

1111
\begin{itemize}
1212

@@ -144,3 +144,31 @@ \section{\module{signal} ---
144144
reference manual for a description of frame objects).
145145
\obindex{frame}
146146
\end{funcdesc}
147+
148+
\subsection{Example}
149+
\nodename{Signal Example}
150+
151+
Here is a minimal example program. It uses the \function{alarm()}
152+
function to limit the time spent waiting to open a file; this is
153+
useful if the file is for a serial device that may not be turned on,
154+
which would normally cause the \function{os.open()} to hang
155+
indefinitely. The solution is to set a 5-second alarm before opening
156+
the file; if the operation takes too long, the alarm signal will be
157+
sent, and the handler raises an exception.
158+
159+
\begin{verbatim}
160+
import signal, os, FCNTL
161+
162+
def handler(signum, frame):
163+
print 'Signal handler called with signal', signum
164+
raise IOError, "Couldn't open device!"
165+
166+
# Set the signal handler and a 5-second alarm
167+
signal.signal(signal.SIGALRM, handler)
168+
signal.alarm(5)
169+
170+
# This open() may hang indefinitely
171+
fd = os.open('/dev/ttyS0', FCNTL.O_RDWR)
172+
173+
signal.alarm(0) # Disable the alarm
174+
\end{verbatim}

0 commit comments

Comments
 (0)