使用 libevent 容易犯的一个错误

使用 libevent 的一个代码片段如下:
  1. struct event ev_accept;
  2. event_set(&ev_accept, listen_fd, EV_READ|EV_PERSIST, on_accept, NULL);
  3. event_add(&ev_accept, NULL);

这段代码是错误的,因为 ev_accept 是在栈上分配的临时变量,但是 ev_accept 实际上是要求在整个程序的生命期中都有效的,且看 libevent 文档中的描述:

 

Event notification
For each file descriptor that you wish to monitor, you must declare an event structure and call event_set() to initialize the members of the structure. To enable notification, you add the structure to the list of monitored events by calling event_add(). The event structure must remain allocated as long as it is active, so it should be allocated on the heap. Finally, you call event_dispatch() to loop and dispatch events.

 

用这种错误的方式,如果内存不被破坏,不一定会出现问题,也就是说,这个错误导致的问题会很隐蔽

 

正确的方式是:

  1. struct event *ev_accept = (struct event*)malloc(sizeof(struct event));
  2. event_set(ev_accept, listen_fd, EV_READ|EV_PERSIST, on_accept, NULL);
  3. event_add(ev_accept, NULL);

实际上导致这个问题出现的原因也很可笑,因为 libevent 自带的 example 程序中就是用的错误的方法,从而毒害了一大批人

你可能感兴趣的:(list,null,文档,Descriptor,events,structure)