Just a quick question about using select()
.
I'm using select()
to read from multiple sockets. When I looked up examples on how to use select()
, a lot of tutorials showed going through for loops and checking for FD_ISSET. The problem I have with those tutorials is that the for loop starts from i = 0
. and checks if the bit has been set for the file descriptor i
using FD_ISSET. Couldn't the for loop start from say your minfd (just like how you would keep track of maxfd)?? Or am I missing something??
Following link is an example of such for loop (look at the fourth example that he gives) https://web.archive.org/web/20100615054620/http://developerweb.net/forum/showthread.php?t=2933
If that was the only example out there that used such for loop, I might understand it was a mistake or bad coding but I've seen several examples of such for loop of uselessly going through literally thousands of sockets and I'm convinced I'm missing something. Any comments or inputs are appreciated.
There's a couple of possible reasons:
stdin
in your list of monitored file descriptors, then you know that minfd
will always be 0 - so there's no point in specifically keeping track of it;minfd
would always be near-zero anyway.Rather than directly looping over file descriptors though, it's actually more usual to loop over some data structure that contains your file descriptors (along with some metadata) - for example, if you kept your outstanding connections in a linked list:
for (conn = list_head; conn; conn = conn->next)
{
if (FD_ISSET(conn->fd, &readfds))
{
/* Do something ... */
}
}