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

本文探讨了在使用sleep函数时遇到的问题,即程序未能按预期时间休眠。通过查阅man手册发现,原因是进程在即将进入休眠状态时被信号唤醒。为确保进程准确休眠指定时间,文章提供了一个解决方案——通过检查sleep函数的返回值并实现循环休眠。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  最近在开发项目的时候遇到一个问题,当使用 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值