【Linux】——sleep无法正常休眠

  最近在开发项目的时候遇到一个问题,当使用 sleep(2) 的时候,程序居然没有按照指定的时间去休眠,但是连续执行两次 sleep(2) 的时候,程序可以正常的休眠 2 秒。真是见鬼了。最后查看了以下 sleep 函数的 man 手册,找到了原因。 man 手册如下:

SYNOPSIS
#include <unistd.h>

unsigned int
sleep(unsigned int seconds);

DESCRIPTION
The sleep() function suspends execution of the calling process until
either seconds seconds have elapsed or a signal is delivered to the
process and its action is to invoke a signal-catching function or to ter-
minate the process. System activity may lengthen the sleep by an inde-
terminate amount.

RETURN VALUES
If the sleep() function returns because the requested time has elapsed,
the value returned will be zero. If the sleep() function returns due to
the delivery of a signal, the value returned will be the unslept amount
(the requested time minus the time actually slept) in seconds.

  也就是说在执行第一个 sleep 的时候,进程正准备休眠的时候,被一个信号唤醒了,再执行第二个 sleep 的时候,没有了信号,进程可以正常的休眠。为了避免这种情况的发生,我们可以根据 sleep 的返回值,重新定义一个函数来让 sleep 真正的休眠指定的秒数。代码如下:

static int sleep_with_restart(int second) {
    int left = second;

    while (left > 0) { 
        left = sleep(left);
    }    

    return 0;
}
原文地址:https://www.cnblogs.com/ngnetboy/p/5733001.html