non-blocking read

Guy Harris guy at rlgvax.UUCP
Tue Feb 7 02:32:17 AEST 1984


The closes thing to a portable non-blocking read is:

#include <fcntl.h>

frobozz(...)
{
	register int i;

	i = fcntl(fdes, F_GETFL, 0);
	fcntl(fdes, F_SETFL, i | O_NDELAY);

	i = read(fdes, buf, count);
#ifdef BSD4_2
	if (i < 0 && errno == EWOULDBLOCK) {
#else
	if (i == 0) {
#endif
		/*
		 * No characters currently available to be read.
		 */
	} else {
		/*
		 * "i" contains the number of characters available to
		 * be read.
		 */
	}

This will work on System III (*if* you fix a bug in the terminal driver),
System V, and 4.2BSD.  *Warning*: the implementation of "fcntl" is 4.2BSD
has a botch, in that the F_SETFL call is *supposed* to set the no-delay
flag on the *file descriptor*, and is *only* supposed to affect *that*
file descriptor (and, on S3/S5/other USG UNIX versions, it does do this);
however, on 4.2BSD, it passes the no-delay flag to the driver which sets
no-delay mode on the terminal port that the file descriptor refers to, so
that *all* file descriptors referring to that terminal port are, in
effect, set to no-delay mode.

	Guy Harris
	{seismo,ihnp4,allegra}!rlgvax!guy



More information about the Comp.unix mailing list