Socket select reducing the number of sockets in file descriptor set
I have a piece of code that accepts 2 connections, creates a file descriptor set with their respective sockets, and passes it to select. But when select returns, the number of file descriptors in the file descriptor set was reduced to 1, and select can just detect received data for the first socket in the fd_array array.
Any ideas where I should开发者_Go百科 look at?
Thanks in advance,
Andre
fd_set mSockets; /* At this point mSockets.fd_count = 2 mSockets.fd_array[0] = 3765 mSockets.fd_array[1] = 2436 */ select(0, & mSockets, 0, 0, 0); /* At this point mSockets.fd_count = 1 mSockets.fd_array[0] = 3765 mSockets.fd_array[1] = 2436 */
That is by design the readfds, writefds and exceptfds paramters of the select functions are in/out paramters.
You should initialize the fd_set before each call to select:
SOCKET s1;
SOCKET s2;
// open sockets s1 and s2
// prepare select call
FD_ZERO(&mSockets);
FD_SET(s1, &mSockets);
FD_SET(s2, &mSockets);
select(0, &mSockets, 0, 0, 0);
// evaluate select results
if (FD_ISSET(s1, &mSockets))
{
// process s1 traffic
}
if (FD_ISSET(s2, &mSockets))
{
// process s2 traffic
}
Additionally cou can check the return value of select. It indicates invalid if you can opertate with the sockets at all. I.e. a zero return indicates, that all FD_ISSET amcros will return 0.
EDIT:
Since readfds, writefds and exceptfds are also out paramters of the select functions, they are modified. The fd_count member indicates how many fd_array members are valid. You should not evaluate fd_array[1]
if fd_count
is less than 2.
精彩评论