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

The first parameter of select, nfds, is supposed to be the maximum file descriptor plus 1, which should be at least 1.
But I have seen some codes set nfds to be 0, is this usage legal?
Plus, the return value of select is set to EINVAL when nfds is negative or timeout contains invalid value. Again, it does not specify what happened when nfds is 0.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • possible duplicate of [Why use select() instead of sleep()?](http://stackoverflow.com/questions/3125645/why-use-select-instead-of-sleep) – hyde May 27 '13 at 07:03

3 Answers3

7

It is possible to use select as an alternative for sleep. I believe it is achieved by specyfying all parameters as 0/NULL except timeout. Consult

Why use select() instead of sleep()?

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114
5

This man page says that

Some code calls select() with all three sets empty, nfds zero, and a non-NULL timeout as a fairly portable way to sleep with subsecond precision.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • It should be noted, in case any newbies find this confusing, that `select` was the *only* portable way to do this before `nanosleep` was widely supported, and that quote has been in that man page for **that long**. –  May 27 '13 at 07:04
3

It waits for the given timeout and then returns 0, or it returns sooner with EINTR. If you think about it, this makes perfect sense and is in fact what the documentation says, even though it does not say it explicitly. The same thing happens if all the sets are NULL or have no bits less than nfds set in them.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226