用C计时器计时

问题描述 投票:2回答:1

我想在特定的持续时间内运行C程序。在此之后,程序应该终止。我搜索了一些关于它的文档,但其中许多使用sleep函数。我不想用它。我想检查当前时间是否大于无限循环中的目标时间。

例如,在代码下面,我的目标时间是5,当运行持续时间大于5时,程序应该终止。

但是代码会导致无限循环。我怎么解决这个问题?

void thread_handler(union sigval sv) {
    char *s = sv.sival_ptr;
    /* Will print "5 seconds elapsed." */
    puts(s);
}

int main(void) {
    char info[] = "5 seconds elapsed.";
    timer_t timerid;
    struct sigevent sev;
    struct itimerspec trigger;
    struct itimerspec triggerAfter;

    memset(&sev, 0, sizeof(struct sigevent));
    memset(&trigger, 0, sizeof(struct itimerspec));

    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_notify_function = &thread_handler;
    sev.sigev_value.sival_ptr = &info;

    timer_create(CLOCK_REALTIME, &sev, &timerid);

    trigger.it_value.tv_sec = 5;

    timer_settime(timerid, 0, &trigger, NULL); 

    timer_gettime(timerid,&trigger);
    while (1) {
        if ((int)trigger.it_value.tv_sec > 5) { //checking the current time is bigger than the target time, it it is then exit from the program
            timer_delete(timerid);
            exit(0);
        }
    }
}
c time timer posix
1个回答
2
投票

如果你想在繁忙的循环中检查和比较,你可以简单地调用clock_gettime并完全避免计时器。计时器的重点是避免这种繁忙的循环。

在您的情况下,您的主线程可以简单地暂停,您可以退出thread_handler函数,该函数由计时器处理程序在专用线程上运行。

#include <time.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void thread_handler(union sigval sv) {
    char *s = sv.sival_ptr;
    /* Will print "5 seconds elapsed." */
    puts(s);
    exit(0);
}

int main(void) {
    char info[] = "5 seconds elapsed.";
    timer_t timerid;
    struct sigevent sev;
    struct itimerspec trigger;
    struct itimerspec triggerAfter;

    memset(&sev, 0, sizeof(struct sigevent));
    memset(&trigger, 0, sizeof(struct itimerspec));

    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_notify_function = &thread_handler;
    sev.sigev_value.sival_ptr = &info;

    if(0>timer_create(CLOCK_REALTIME, &sev, &timerid)) return perror("timer_create"),1;

    trigger.it_value.tv_sec = 5;

    if(0>timer_settime(timerid, 0, &trigger, NULL)) return perror("timer_settime"),1;

    pause();

}

如果您仍想忙着检查,则需要在等待循环中使用timer_gettime。只调用一次就不会使trigger对象自动更新。

© www.soinside.com 2019 - 2024. All rights reserved.