View Single Post
Old 05-17-2005, 01:03 PM   #7 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,693
redhead is on a distinguished road
For nonblocking read in C, if it's a POSIX environment, then this can be of use:
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int stdin_init(int fd)
{
    /* set file to non-blocking */
    int flags = fcntl(fd, F_GETFL, 0);
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
	return -1;
    return 0;
}

/* Read bytes from stdin, using non-blocking if possible. */
int stdin_read(char *buf, int len, int interactive, int fd)
{
    fd_set rfds;
    int count;
    count = read(fd, buf, len);
    if (count < 0) {	/* error or EWOULDBLOCK */
	if (errno != EAGAIN)
	    return -1;
        /* Wait until at least one byte is available */
	FD_ZERO(&rfds);
	FD_SET(fd, &rfds);
	select(1, &rfds, NULL, NULL, NULL);
        count = read(fd, buf, len);
	if (count < 0)
	    count = 0;	/* EOF */
    }
    return count;
}
And it can be used in your code instead of your getc() loop, something like this:
Code:
...
int init_return;
char buffer[SOME_LENGTH];
...
if( ! init_return = init_stdin(stdin) )
{
   while(0 < stdin_read(buffer, 1, init_return, stdin))
    {
           /* do something with buffer[0] */;
    }
}
...
This will only work in a POSIX environment, and on some systems, like the AIX, the stdout stream must be set to non blocking aswell.
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote