linux select 进程阻塞,程序中用sleep和select阻塞休眠的区别

程序调用sleep就是放弃cpu执行,进入阻塞状态,但是sleep的秒数过后,有可能有很多进程或线程在竞争cpu,而且优先级都比当前程序高,导致当先进程或线程无法立即执行,这是导致sleep不准确的一个原因。

gnu里介绍sleep:

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn’t use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval. Otherwise, sleep can return sooner if a signal arrives; if you want to wait for a given interval regardless of signals, use select (see Waiting for I/O) and don’t specify any descriptors to wait for.

Resist the temptation to implement a sleep for a fixed amount of time by using the return value of sleep, when nonzero, to call sleep again. This will work with a certain amount of accuracy as long as signals arrive infrequently. But each signal can cause the eventual wakeup time to be off by an additional second or so. Suppose a few signals happen to arrive in rapid succession by bad luck—there is no limit on how much this could shorten or lengthen the wait.

Instead, compute the calendar time at which the program should stop waiting, and keep trying to wait until that calendar time. This won’t be off by more than a second. With just a little more work, you can use select and make the waiting period quite accurate. (Of course, heavy system load can cause additional unavoidable delays—unless the machine is dedicated to one application, there is no way you can avoid this.)

On some systems, sleep can do strange things if your program uses SIGALRM explicitly. Even if SIGALRM signals are being ignored or blocked when sleep is called, sleep might return prematurely on delivery of a SIGALRM signal. If you have established a handler for SIGALRM signals and a SIGALRM signal is delivered while the process is sleeping, the action taken might be just to cause sleep to return instead of invoking your handler. And, if sleep is interrupted by delivery of a signal whose handler requests an alarm or alters the handling of SIGALRM, this handler and sleep will interfere.

On GNU systems, it is safe to use sleep and SIGALRM in the same program, because sleep does not work by means of SIGALRM.

有的系统使用alarm,pause或sigsuspend来实现sleep,这样使sleep受到SIGALRM信号影响。各个系统的sleep版本不一。

ldd --version能看到libc版本,gnu的sleep已经不依靠SIGALRM实现,所以SIGALRM对sleep没有影响。