最近在开发项目的时候遇到一个问题,当使用 sleep(2) 的时候,程序竟然没有按照指定的时间去休眠,可是连续执行两次 sleep(2) 的时候,程序能够正常的休眠 2 秒。真是见鬼了。最后查看了如下 sleep 函数的 man 手册,找到了缘由。 man 手册以下:函数
SYNOPSIS
#include <unistd.h>spa
unsigned int
sleep(unsigned int seconds);rest
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.code
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.blog
也就是说在执行第一个 sleep 的时候,进程正准备休眠的时候,被一个信号唤醒了,再执行第二个 sleep 的时候,没有了信号,进程能够正常的休眠。为了不这种状况的发生,咱们能够根据 sleep 的返回值,从新定义一个函数来让 sleep 真正的休眠指定的秒数。代码以下:进程
static int sleep_with_restart(int second) { int left = second; while (left > 0) { left = sleep(left); } return 0; }