最近在開發項目的時候遇到一個問題,當使用 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; }