The select function blocks the calling process until there is activity on any of the specified sets of file descriptors [...] A file descriptor is considered ready for reading if a read call will not block. (See: https://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html)
So I expected, that select in the following program would immediately return in the 2nd, ... iteration, if you enter a string > 4 characters in the first iteration. However it does not. Just after pressing any other key after the first output it continues to handle all the remaining input. Why?
Sample output:
./selectTest
12345678900
Keyboard input received: 1234
A
Keyboard input received: 5678
Keyboard input received: 900
Keyboard input received: A
Code
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
fd_set rfds;
char buf[100];
while(1)
{
FD_ZERO(&rfds);
FD_SET(fileno(stdin), &rfds);
if(-1 == select(FD_SETSIZE, &rfds, NULL, NULL, NULL))
{
perror("select() failed\n");
}
if(FD_ISSET(fileno(stdin), &rfds))
{
printf("Keyboard input received: ");
fgets(buf, 5, stdin);
printf("%s\n", buf);
}
}
return 0;
}
(I know, that I should not use select() anymore, but I am learning for an exam and we have to ...)