Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous, timed function calling in C on Linux?

What is the easiest, most effective way in C on Linux to asynchronously call a function after a certain delay (like JavaScript's setTimeout) or set a repetitive timer call it periodically (similar to setInterval)?

Though this question applies to Linux, I hope there is a method that is cross-platform.

like image 861
Delan Azabani Avatar asked Sep 14 '10 10:09

Delan Azabani


2 Answers

The simplest Linux specific solution is to use the alarm function:

void alarm_handler (int signum)
{
    printf ("Five seconds passed!\n");
}

signal (SIGALRM, alarm_handler);
alarm (5);

getitimer and setitimer functions can be used to create timers with higher-precisions. (more...).

like image 169
Vijay Mathew Avatar answered Sep 20 '22 11:09

Vijay Mathew


There are two ways to go about it:

First, as mentioned in another answer, is signals triggered using alarm() or setitimer(). Both functions are available in any OS that adheres to POSIX; there's a third function called ualarm() which was obsoleted in 2008. The down side is that it's unsafe to do anything significant (e.g., I/O or other system calls) in a signal handler, so really all you want to do is maybe set a flag and let something else pick it up.

Second is to use a thread that sleeps for a certain interval and then calls your function. POSIX standardized threads as an extension in the early 1990s, and most modern OSes that support threads support POSIX threads. The pitfall here is that you have to understand the implications of having two execution contexts share the same data space and design your program accordingly or you're going to run into problems that can be a nightmare to debug.

Be aware that alarms and sleeps only promise to do what they do after at least the specified amount of time has elapsed, so you're not guaranteed the kind of accuracy you'd get on a real-time operating system.

like image 42
Blrfl Avatar answered Sep 16 '22 11:09

Blrfl