Search code examples
socketsnetwork-programmingwinsockwinsock2

"nfds" parameter in select() in sockets programming


I never really got the idea behind this parameter, what is it good for? I also noticed this parameter is ignored in WinSock2, why is that? Do Unix systems use this parameter or do they ignore it as well?


Solution

  • Windows' implementation of select() uses linked lists internally, so it doesn't need to use the nfds parameter for anything.

    On other OS's, however, the fd_set struct is implemented to hold an array of bits (one bit per socket). For example, here is how it is declared (in sys/_types/_fd_def.h) under MacOS/X:

    typedef struct fd_set {
        __int32_t fds_bits[__DARWIN_howmany(__DARWIN_FD_SETSIZE, __DARWIN_NFDBITS)];
    } fd_set;
    

    ... and in order to do the right thing, the select() call will have to loop over the bits in the array to see what they contain. By supplying select() with the nfds parameter, we tell the select() implementation that it only needs to iterate over the first (nfds) bits of the array, rather than always having to iterate over the entire array on every call. This allows select() to be more efficient than it would otherwise be.