c - 实时感知 sleep() 调用?

标签 c linux sleep clock suspend

我写了一个实用程序来与 TomTom GPS watches over Bluetooth 对话,并试图让它作为一个运行后忘记后台守护进程很好地运行。

程序定期与 GPS 设备通信,然后 sleep s 一段时间,直到再次需要它。

我注意到 sleep() 与系统挂起有奇怪的交互:当我进入系统挂起(运行 Linux 3.16.0 内核的笔记本电脑)然后唤醒计算机备份时,sleep 似乎没有注意到暂停时间。例如,采用以下 sleep.c:

#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char**argv)
{
    time_t t=time(NULL);
    printf("sleep at: %s", ctime(&t));

    sleep(atoi(argv[1]));

    t=time(NULL);
    printf("wake at: %s", ctime(&t));
}
dlenski@dlenski-ultra:~$ 

编译运行,中途休眠;

$ gcc sleep.c -o sleep
$ ./sleep 30
sleep at: Fri Aug 21 21:05:36 2015
<suspend computer for 17 seconds>
wake at: Fri Aug 21 21:06:23 2015

是否有以时钟时间感知而非系统运行时间感知的方式暂停程序执行的正确方法-知道吗?

(我还尝试了 usleepnanosleepalarm,发现它们的行为相似。)

更新: setitimer , 正如 @HuStmpHrrr 所建议的那样,听起来很有前途......但似乎有同样的问题。

当我在中间暂停时,此版本暂停超过请求的 30 秒...

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>

void sighandler() {}

int main(int argc, char**argv)
{
    time_t t=time(NULL);
    printf("sleep at: %s", ctime(&t));

    signal(SIGALRM, sighandler);
    struct itimerval timer = {.it_interval={0,0},
                              .it_value={atoi(argv[1]),0}};
    setitimer(ITIMER_REAL, &timer, NULL);
    pause();

    t=time(NULL);
    printf("wake at: %s", ctime(&t));
}

最佳答案

一些解决方案和潜在的解决方案:

循环休眠,查看真实耗时

几乎肯定有更好的方法来做到这一点——或者应该有!——但目前我的应用程序可以接受以下解决方案:

  • 当需要长时间休眠(>30 秒)时,我重复执行 sleep(30),检查 真实 已用时间(time(NULL)-start_time) 不长于所需的总暂停时间。

  • 这样,如果系统暂停,比如说 3 小时,而所需的程序暂停时间为 1 小时,则暂停造成的额外延迟不会超过 30 秒。

实现代码:

void nullhandler(int signal) {}

int isleep(int seconds, int verbose)
{
    if (verbose) {
        fprintf(stderr, "Sleeping for %d seconds...", seconds);
        fflush(stderr);
    }
    signal(SIGALRM, nullhandler);

    // weird workaround for non-realtime-awareness of sleep:
    // https://stackoverflow.com/questions/32152276/real-time-aware-sleep-call
    int res=0, elapsed=0;
    for (time_t t=time(NULL); (elapsed<seconds) && (res<=0); elapsed=time(NULL)-t)
        res = sleep((seconds-elapsed > 30) ? 30 : seconds-elapsed);

    signal(SIGALRM, SIG_IGN);
    if (res && verbose)
        fprintf(stderr, "%s\n\n", res ? " woken by signal!" : "");
    return (res>0);
}

唤醒回调

@Speed8ump建议为系统唤醒通知注册回调。 This thread over at AskUbuntu展示了如何去做。一个很好的解决方案,但我现在想避免将相对较低级别的代码过于强烈地绑定(bind)到特定的桌面环境。

timer_settime

在我看来,这是最优雅、最正确的解决方案,由 @NominalAnimal 建议.它使用 timer_settime()和来自 librt 的 friend 。

请注意,为了使它在系统挂起时正常工作,您必须根据 timer_settime 文档将 CLOCK_REALTIMETIMER_ABSTIME 一起使用:

If the value of the CLOCK_REALTIME clock is adjusted while an absolute timer based on that clock is armed, then the expiration of the timer will be appropriately adjusted. Adjustments to the CLOCK_REALTIME clock have no effect on relative timers based on that clock.

这是一个演示(链接到 librt,例如 gcc -lrt -o sleep sleep.c):

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>

void sighandler(int signal) {}

void isleep(int seconds)
{
    timer_t timerid;
    struct sigevent sev = { .sigev_notify=SIGEV_SIGNAL,
                            .sigev_signo=SIGALRM,
                            .sigev_value=(union sigval){ .sival_ptr = &timerid } };
    signal(SIGALRM, sighandler);
    timer_create(CLOCK_REALTIME, &sev, &timerid);

    struct itimerspec its = {.it_interval={0,0}};
    clock_gettime(CLOCK_REALTIME, &its.it_value);
    its.it_value.tv_sec += seconds;
    timer_settime(timerid, TIMER_ABSTIME, &its, NULL);
    pause();
    signal(SIGALRM, SIG_IGN);
}

int main(int argc, char**argv)
{
    time_t t=time(NULL);
    printf("sleep at: %s", ctime(&t));

    isleep(atoi(argv[1]));

    t=time(NULL);
    printf("wake at: %s", ctime(&t));
}

关于c - 实时感知 sleep() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152276/

相关文章:

linux - 重命名批量文件并更改某些前缀并保存它们

android - 在android中以两秒的间隔时间按顺序显示图像

c - 使用 perf 或其他方式获取 C 程序的运行时间(或其他统计信息)

c - 通过检查核心和调用堆栈了解使用 GDB 的 C 指针

linux - 如何将目录更改为在 linux 中运行作业(PID)的目录?

c++ - 通过 C++ 获取 micro SD 卡的大小

powershell - 每次系统从 sleep 中唤醒时都需要运行 powershell 脚本

php - 我应该使用 Sleep() 还是拒绝它们

c - OpenMP 和带有 continue 语句的嵌套 for 循环

c - 文件作为 Win32 应用程序的参数