tags:

views:

590

answers:

3

select() is defined as :

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);

nfds represents the highest file descriptor in all given sets plus one. I would like to know why is this data required for select() when the fd_set information is available.

If the FDs in the set are say, 4, 8, 9 ,the value of nfds would be 10. Would select() moniter fds 9,8,7,6,5,4 ?

A: 

Select monitors those FDs which you have enabled using the FD_SET macro. If you do not enable any FD for monitoring, select() does not monitor any.

"nfds" is definitely redundant, but it is part of the select() interface, so you need to use it :)

Anyway, if you have {4, 8, 9} in the set, you set nfds to 10 (as you mentioned), and select() will only monitor the three FDs 4, 8 and 9.

antti.huima
A: 

It's probably an optimization so that select doesn't have to walk through the whole fd_set to find out which descriptors are actually used. Without that parameter, select would always need to look at the whole set to find which descriptors are actually used in the call, with the parameter, some of that work can be omitted.

sth
+5  A: 

The catch is that fd_set is not really a "set" in the way you're thinking. The behind-the-scenes detail is that the implementation of an fd_set is just an integer that is used as a bitfield. In other words, executing

fd_set foo;
FD_CLEAR(&foo);
FD_SET(&foo, 3);

Sets foo to decimal value 8 - it sets the fourth-least-singificant bit to 1 (remember that 0 is a valid descriptor).

FD_SET(&foo, 3);

is equivalent to

foo |= (1 << 3);

So in order for select to work right, it needs to know which bits of the fd_set are bits that you care about. Otherwise there would be no way for it to tell a zero bit that is "in" the set but set to false from a zero bit that is "not in" the set.

In your example, a fd_set with 4, 8, and 9 set and n = 10 is interpreted as "A set with 10 entries (fds 0-9). Entries 4, 8, and 9 are true (monitor them). Entries 1,2,3,5,6,7 are false (don't monitor them). Any fd value greater than 9 is simply not in the set period."

Tyler McHenry