I’ve read all the information I found regarding this matter and unfortunately none of it helps. I’ve written this small function as a non-blocking version of fgetc:
char nonblocking_fgetc(FILE *stream){
static struct pollfd pfd;
pfd.fd = fileno(stream);
pfd.events=POLLIN;
poll(&pfd, 1, 1);
return ((pfd.revents&POLLIN)?fgetc(stream):-1);
}
This function should return a character if it is present in stream, or a -1 otherwise. It works as expected for the first call. However, any subsequent call returns -1.
The function above is cleaned up version. My version has many tests which check for polling errors. Nether POLLERR is set or a negative value is returned.
example:
main contains this small while loop:
while(1){
c=nonblocking_fgetc(stdin);
if (c!=-1) {fputc(c, stdout);fflush(stdout);}
}
running echo "Test" | ./a.out would yield only T and then loops without any further output.
I would appreciate it if anyone can shed some light on this.
The
<stdio.h>file streams are buffered. See setbuf for more. You could use directly the read syscall.