Why use select() instead of sleep()? Why use select() instead of sleep()? multithreading multithreading

Why use select() instead of sleep()?


Select allow for accurate sub second wait, and is more portable than sleep. There are other ways to wait, see this question.

But the timeout parameter of select should not be a float but a pointer to struct timeval. I'm surprised the code you show even compiles. More : this strange conditional select is followed by an unconditional sleep(1). Looks pointless to me.


Using select() with NULL rfds, wfds and efds is an idiomatic way of portably sleeping with subsecond resolution.


Well, sleep(3) may be implemented by using signals. It depends on the platform.

When you use select(2) and poll(2), you know that no signals will be involved, which is often very useful. For example, if you are using alarm(2), you should not use sleep(3) as well, because "mixing calls to alarm and sleep is a bad idea" (according to the man page.)

Also, select and poll give you millisecond granularity when sleeping, but sleep only has a granularity in terms of seconds.