From 42db27fedc6d1e1600eeb6fa68e7925890350255 Mon Sep 17 00:00:00 2001 From: "Andrew M. Kuchling" Date: Tue, 18 Aug 1998 19:38:54 +0000 Subject: [PATCH] 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. --- Doc/lib/libsignal.tex | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/Doc/lib/libsignal.tex b/Doc/lib/libsignal.tex index 78f38eda2ff..94ad536ab3e 100644 --- a/Doc/lib/libsignal.tex +++ b/Doc/lib/libsignal.tex @@ -6,7 +6,7 @@ \modulesynopsis{Set handlers for asynchronous events.} This module provides mechanisms to use signal handlers in Python. -Some general rules for working with signals handlers: +Some general rules for working with signals and their handlers: \begin{itemize} @@ -144,3 +144,31 @@ The \module{signal} module defines the following functions: reference manual for a description of frame objects). \obindex{frame} \end{funcdesc} + +\subsection{Example} +\nodename{Signal Example} + +Here is a minimal example program. It uses the \function{alarm()} +function to limit the time spent waiting to open a file; this is +useful if the file is for a serial device that may not be turned on, +which would normally cause the \function{os.open()} to hang +indefinitely. The solution is to set a 5-second alarm before opening +the file; if the operation takes too long, the alarm signal will be +sent, and the handler raises an exception. + +\begin{verbatim} +import signal, os, FCNTL + +def handler(signum, frame): + print 'Signal handler called with signal', signum + raise IOError, "Couldn't open device!" + +# Set the signal handler and a 5-second alarm +signal.signal(signal.SIGALRM, handler) +signal.alarm(5) + +# This open() may hang indefinitely +fd = os.open('/dev/ttyS0', FCNTL.O_RDWR) + +signal.alarm(0) # Disable the alarm +\end{verbatim}