Non-blocking tty read

G.TOMASEVICH 54394gt at hocda.UUCP
Tue Feb 7 06:42:39 AEST 1984


Recently I posted an article to 'net.unix-wizards' on nonblocking terminal
reads.  We have USG 4.2 UNIX, which has 'struct termio'; if you have
an oldter system with 'struct sgtty' you cannot do it.  One changes to
raw mode by saving the contents of the struct for line 0, then changes
some constants.  Assume you have the following code:

#include <termio.h>
struct termio svt;		/* for saving initial parameters */
struct termio stt;		/* for changing line parameters */

	...
	ioctl(0,TCGETA,&svt);	/* save old */
	stt.c_iflag = stt.c_oflag = stt.c_lflag = 0;
	stt.c_cflag = (svt.c_cflag&CBAUD)|CS8|CREAD|CLOCAL; /* direct line */
	stt.c_cc[VMIN] = 0;	/* no chars needed for read() to return */
	stt.c_cc[VTIME] = 0;	/* timeout limit = 0 */
	ioctl(0,TCSETA,&stt);

To try to get a char, do the following:

	char key;
	if(read(0,&key,1) == 1)
		there is a char;
	else
		there is no char;

If there is a character available, then the read() returns 1,
so you can test the return value.  I use it in conjuction with a DR11-W
read/write program, which must poll the DR11-W status while waiting
for characters to be typed.  Of course, you hog the computer while running
such a loop.  If you want a blocking read, then set stt.c_cc[VMIN] = 1;
I change back and forth, depending on whether anything besides keyboard
input is happening at any particular instant.

To avoid lousing up your line, catch all signals so you can do

	ioctl(0,TCSETA,&svt);
	and then an abort() if you want a core dump;

before the process exits;



More information about the Comp.unix mailing list