misteryes
misteryes

Reputation: 2287

libevent: timeout event is not triggered

I'm writing a program and use libevent.

I add an event

struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 10000;
...
...
event_set(&ev, fd, EV_READ|EV_TIMEOUT|EV_PERSIST, callback, NULL);
event_add(&ev, &tv);

but I notice that if I replace &tv with NULL, namely I don't want a timeout event, then the program works fine, the event ev is triggered when the fd is readable, however, if it is &tv not NULL, the event is only triggered for the first time when fd is readable.

What is the reason for this? is it that the timeout value is too small? what is the minimum timeout value for libevent, epoll, select. etc?

thanks!

Upvotes: 2

Views: 2396

Answers (1)

amyangfei
amyangfei

Reputation: 96

What about this , libevent timeout sample

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <event.h>

#define BUFSIZE 256
#define TIMEOUT_SEC 3

void read_handler(int fd, short event, void *arg)
{
  char buffer[BUFSIZE];
  ssize_t read_len;
  read_len = read(fd, buffer, BUFSIZE);
  buffer[read_len] = '\0';
  printf("%s", buffer);
}

void event_handler(int fd, short event, void *arg)
{
  if (event & EV_TIMEOUT) {
    printf("timeout\n");
    //exit(1);
  } else if (event & EV_READ) {
    read_handler(fd, event, arg);
  }
}

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

  tv.tv_sec = TIMEOUT_SEC;
  tv.tv_usec = 0;

  ev_base = event_base_new();
  ev = event_new(ev_base,
                 fileno(stdin),
                 EV_TIMEOUT | EV_READ | EV_PERSIST,
                 event_handler,
                 NULL);
  event_add(ev, &tv);
  event_base_dispatch(ev_base);

  event_free(ev);
  event_base_free(ev_base);

  return 0;
}

Just remove the code "exit(1)" in line 22 or do something else when timeout.event will be always triggered when fd is readable.

Upvotes: 1

Related Questions