timeout on read; Bourne Shell

heinz at cc.univie.ac.at heinz at cc.univie.ac.at
Mon May 27 20:42:58 AEST 1991


In <1991May26.165314.21533 at midway.uchicago.edu> goer at ellis.uchicago.edu (Richard L. Goerwitz) writes:

>Is there any elegant way to achive a timeout on a read within
>a shell script?  Perhaps even "fairly elegant" would do.  Even
>a kludge?
>-- 

>   -Richard L. Goerwitz              goer%sophist at uchicago.bitnet
>   goer at sophist.uchicago.edu         rutgers!oddjob!gide!sophist!goer

Here is a quick 'n' dirty hack. I'm quite sure there are more elegant solutions,
but this is the first that came into my mind.

----- Start of sample script -----
	#! /bin/sh --
	trap ":" 2
	(sleep 1; kill -2 $$) &
	read input
	trap 2
	echo End of script
----- End of sample script -----

Explanation:

1) Use the Bourne Shell as interpreter (you may use any other shell as well).

2) The empty command (:) is associated with signal number 2. You may
use any other signal as well, barring signal 9. You may also associate any other
command with the signal, like
	trap "echo Ouch! That hurt!" 2
In the above script, no action needs to be performed upon receipt of the signal,
so the empty command is used. You can't use empty quotes, since this would mean
to ignore the signal, which would be wrong here.

3) A subshell is started in the background, which performs the following
actions: a) sleep 1 second (insert your timeout here); b) send signal number 2
to the parent shell ($$ is expanded to the PID of the shell executing the
script) after waking up from the sleep.

4) Meanwhile, the 'main' shell executes the read (and, of course, blocks
waiting for input). Upon receipt of the signal from the background process,
it interrupts the read, executes the action associated with the signal in the
trap statement (which is nothing in this example), and continues execution of
the script.

5) In case you have to, reset the action for the signal you used to the default
action.

6) Continue with your script.

Hope this helps. I'd appreciate it if someone posted a more elegant solution
(without sub-processes and stuff like that :)

Greetings,
HH
--
--------------------------------------------------------------------------------
---/     Heinz M. Herbeck                    /    Trust me, I know    /       /-
--/     heinz at sophie.pri.univie.ac.at       /    what I'm doing !    /       /--
-/     Vienna University, Austria          /    (Sledge Hammer)     /       /---
--------------------------------------------------------------------------------



More information about the Comp.unix.questions mailing list