Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a method every x seconds in C

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.

like image 227
Feras Wilson Avatar asked Dec 17 '12 23:12

Feras Wilson


1 Answers

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.

like image 73
Adam Rosenfield Avatar answered Oct 18 '22 14:10

Adam Rosenfield