select() function not removing unresponsive file descritors

This program is supposed to wait for user input for 2.5 secs before printing time out. or print "A key was pressed!" if user presses a key within 2.5 secs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<winsock.h>
#include<iostream.h>
#include<conio.h>
 // file descriptor for standard input
int main(void)
{
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 500000;
FD_ZERO(&readfds);
int STDIN =_fileno(stdin);
FD_SET(STDIN, &readfds);
// don’t care about writefds and exceptfds:
select(STDIN+1, &readfds, NULL, NULL, &tv);
if (FD_ISSET(STDIN, &readfds))
cout<<"A key was pressed!\n";
else
cout<<"Timed out.\n";
getch();
return 0;
}



It always prints "A key was pressed!" no matter what and that too immediatrly.
The issue is what does FD_ISSET() do:

man page wrote:
FD_ISSET(fd, &fdset) is non-zero if fd is a member of fdset, zero otherwise.
In other words: It checks if STDIN is set to readfds and that's true
Last edited on
But since i did not press any key stdin should have been removed by select() at after 2.5 secs from readfds. But it didn't
select() also returns the number of file descriptors signalled, so you don't need to check the descriptor in this case, you can just check what select() returns, zero for timeout, one for stdin being available.

I've just noticed that you're running on Windows. I don't think select() works on file descriptors on Windows, it only works on sockets. On Unix (and Linux), a socket is a file descriptor. But other OSs implement sockets seperately, outside of the kernel; in which case a socket and file descriptor are different things.
kbw if select() does not work for all file descriptors(like stdin) on windows, then what is the alternative function for select() ?
Topic archived. No new replies allowed.