timeout on read; Bourne Shell

Martin Weitzel martin at mwtech.UUCP
Mon May 27 23:13:43 AEST 1991


In article <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?

I just hacked the following short C-Program which may solve your problem.
All you need to know to use it is in the comment at the beginning.

--- cut here ---- cut here ---- cut here ---- cut here ---- cut here --
/*
 * tmdrd -- timed read
 *
 * Can be called in shell scripts to read some variable x as follows:
 *
 * x=`tmdrd`		# times out after 30 seconds, returns empty string
 * x=`tmdrd -12`	# times out after 12 seconds, returns empty string
 * x=`tmdrd -60 y`	# times out after 60 seconds, returns "y"
 *
 * BUGS: This program is a quick hack. There could certainly be many
 * improvements, e.g. checking whether the reason for the bad read was
 * really a timeout, better handling of defaults, flushing of the input
 * waiting before the read and after a time out has hit ...
 *
 * AUTHOR: Martin Weitzel (martin at mwtech.UUCP)
 *
 * Permission to distribute, use, and modify this program is granted to
 * everyone, with one MAJOR EXCEPTION: The program may NOT be used by any
 * company that tries to enforce software patents on their work or copy-
 * rights on their user interfaces. (Sorry, I'm not willing to cooperate
 * with those who are not willing to cooperate with the rest of the world.)
*/

static char USAGE[] = "tmdrd [-seconds] [default]";

#include <stdio.h>
#include <signal.h>

#define TM_DEFAULT 30	/* default time out period */
#define MAX_ANSWER 1000	/* maximum acceptable answer */

static void catcher(sig)
	int sig;
{
	/*empty*/
}
	
main(argc, argv)
	int argc;
	char **argv;
{
	int secs = TM_DEFAULT;
	char buffer[MAX_ANSWER];
	char *answer = "";
	int nread;

	/* check usage */
	if (argc > 3) {
		fprintf(stderr, "Usage %s\n", USAGE);
		exit(1);
	}
	/* extract arguments */
	if (argc > 1 && argv[1][0] == '-') secs = atoi(argv[1] + 1);
	if (argc > 1 && argv[argc-1][0] != '-') answer = argv[argc-1];

	/* wait for input */
	signal(SIGALRM, catcher);
	alarm(secs);
	nread = read(0, buffer, MAX_ANSWER);
	alarm(0);

	/* check for timeout condition */
	if (nread > 0) {
		buffer[nread-1] = '\0'; /* delete newline */
		answer = buffer;
	}

	/* write answer to stdout */
	printf("%s", answer);

	exit(0);
}
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.questions mailing list