Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libevent: make timer persistent

Tags:

c

timer

libevent

I have the following code:

#include <stdio.h>
#include <sys/time.h>
#include <event.h>

void say_hello(int fd, short event, void *arg){
        printf("Hello\n");
}

int main(int argc, const char* argv[])
{
  struct event ev;
  struct timeval tv;

  tv.tv_sec = 3;
  tv.tv_usec = 0;

  event_init();
  evtimer_set(&ev,say_hello,NULL);
  evtimer_add(&ev, &tv);
  event_dispatch();

  return 0;
}

Problem is "hello" gets printed once and then the program exits...

I want it to output "hello" indefinitely.

How to do this? Many thanks in advance,

like image 649
Eamorr Avatar asked Dec 06 '22 10:12

Eamorr


1 Answers

Just to clarify Basile's solution:

I was confused as well until I realized that "timer" in this context refers to a single shot timer. What we need is an interval timer; which requires the EV_PERSIST flag in libevent.

struct timeval time;
time.tv_sec = 1;
time.tv_usec = 0;

event_set(&my_event, 0, EV_PERSIST, my_function, NULL);
evtimer_add(&my_event, &time);
like image 123
seo Avatar answered Dec 14 '22 22:12

seo