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.