I want to write a C program that would periodically perform some task (say, print something on console).
I have implemented it using nanosleep as below. Every 500ms the function 'func' is called.
#include <stdio.h>
#include <time.h>
void func(void);
int main()
{
struct timespec mytimespec;
mytimespec.tv_sec = 0;
mytimespec.tv_nsec = 500000000; /* 500 ms */
while(1)
{
func();
nanosleep(&mytimespec,NULL);
}
return 0;
}
void func(void)
{
printf("This would be printed periodically\n");
}
Above is working correctly. However I have some doubts:-
Would it work accurately if there are multiple threads and one thread relies on nanosleep to do the periodic task?
Is there a way to spawn a periodic thread in linux? Or, to use some timer callback?
You should read time(7) (and perhaps signal(7)...). You probably want some event loop (at least if your program is doing some input). That loop is based upon a multiplexing syscall like poll(2) (see also this and that answers). Many libraries provide event loops, notably libevent, libev, Gtk/Glib, Qt, ...
On Linux you could be also interested by timerfd_create(2) (in addition of other more traditional solutions).
And read Advanced Linux Programming
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With