使用 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.

 

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

 

正确的方式是:

    • struct event *ev_accept = (struct event*)malloc(sizeof(struct event));
    • event_set(ev_accept, listen_fd, EV_READ|EV_PERSIST, on_accept, NULL);
    • event_add(ev_accept, NULL);

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值