Execute a method every x seconds in C

后端 未结 4 1003
别那么骄傲
别那么骄傲 2021-01-06 00:29

Is there an example of a working timer that executes some function every x amount seconds using C.

I\'d appreciate an example working code.

4条回答
  •  悲&欢浪女
    2021-01-06 00:57

    You could spawn a new thread:

    void *threadproc(void *arg)
    {
        while(!done)
        {
            sleep(delay_in_seconds);
            call_function();
        }
        return 0;
    }
    ...
    pthread_t tid;
    pthread_create(&tid, NULL, &threadproc, NULL);
    

    Or, you could set an alarm with alarm(2) or setitimer(2):

    void on_alarm(int signum)
    {
        call_function();
        if(!done)
            alarm(delay_in_seconds);  // Reschedule alarm
    }
    ...
    // Setup on_alarm as a signal handler for the SIGALRM signal
    struct sigaction act;
    act.sa_handler = &on_alarm;
    act.sa_mask = 0;
    act.sa_flags = SA_RESTART;  // Restart interrupted system calls
    sigaction(SIGALRM, &act, NULL);
    
    alarm(delay_in_seconds);  // Setup initial alarm
    

    Of course, both of these methods have the problem that the function you're calling periodically needs to be thread-safe.

    The signal method is particularly dangerous because it must also be async-safe, which is very hard to do -- even something as simple as printf is unsafe because printf might allocate memory, and if the SIGALRM interrupted a call to malloc, you're in trouble because malloc is not reentrant. So I wouldn't recommend the signal method, unless all you do is set a flag in the signal handler which later gets checked by some other function, which puts you back in the same place as the threaded version.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题