Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodic Task in Linux

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?

like image 827
Siddhartha Ghosh Avatar asked Feb 01 '26 00:02

Siddhartha Ghosh


1 Answers

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

like image 129
Basile Starynkevitch Avatar answered Feb 02 '26 16:02

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!