Barien KH Barien KH -4 years ago 87
C Question

Added the same socket fd twice to fd_set then calling select

I'm been reading the man page for select (from difference sources) and can't seem to get a straight explanation.

Lets say I have an already connected socket like this:

s1 = socket(...);
connect(s1, ...)...


Now lets say I add the socket twice (eg: mistakenly) to the same fd_set like so:

fd_set readfds;


FD_ZERO(&readfds);
FD_SET(s1, &readfds);
....
FD_SET(s1, &readfds);


Now I call select:

int rv = select(n, &readfds, NULL, NULL, &tv);

if (rv == -1) {
perror("select"); // error occurred in select()
}
else if (rv == 0) {
printf("Timeout occurred! No data after 10.5 seconds.\n");
}
else {
// one the descriptors have data
.....
}


If data is send from the socket, will select have set both FDs as ready or only the first one that I've added?

Answer Source

Since FD_SET is a set (in the mathematical meaning of the word), any file descriptor is either in it or it is not. Adding the same descriptor to the set more than once has no effect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download