non-blocking read

moss%brl-vld at sri-unix.UUCP moss%brl-vld at sri-unix.UUCP
Wed Feb 8 02:30:09 AEST 1984


From:      Gary S Moss ~Software Development Team~ <moss at brl-vld>

The following is a way to do non-blocking reads on System V.  Actually,
I implemented it on Doug Gwyn's System V emulation on top of Berkeley
4.2 so its portable in the sense that System V is a standard of sorts
and with Doug's emulation it travels still further.

Let me mention that it is really frustrating that in order to figure
out how to do this I had to jump around from fcntl(2) to ioctl(2) to
read(2) in the User's Manual - System V and then to termio(7) in the
Administrator's Manual - System V.

#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>

static struct termio	termBuf;	/* Termio buffer.		*/
static unsigned short	localModes;	/* Save local modes.		*/
static int		filStat;	/* Save file status flags.	*/

main() {
	int	c, done;

	(void) ioctl( 0, TCGETA, &termBuf ); /* Get termio parameters.	*/
	localModes = termBuf.c_lflag;	     /* Save local modes.	*/
	termBuf.c_lflag &= ~ICANON;	     /* Raw mode ON.		*/
	termBuf.c_lflag &= ~ECHO;	     /* Echo mode OFF.		*/
	(void) ioctl( 0, TCSETA, &termBuf ); /* Set local modes.	*/

	filStat = fcntl( 0, F_GETFL, 0 );    /* Save file status flags.	*/
	(void) fcntl( 0, F_SETFL, O_NDELAY );/* Set non-blocking read.	*/

	for( done = 0; ! done ; ) {
		if( read( 0, &c, 1 ) )
			done = ! do_something_with( c );
		else
			update_screen();
	}

	termBuf.c_lflag = localModes;	     /* Retrieve old setting.	*/
	(void) ioctl( 0, TCSETA, &termBuf ); /* Reset local modes.	*/
	(void) fcntl( 0, F_SETFL, filStat ); /* Restore file status.	*/
	exit( 0 );
}

- Moss.



More information about the Comp.unix mailing list