libevent初步认识

一、下载安装

1. 在官网上下载对应版本的包  https://libevent.org/
2. tar -zxvf /your path/libevent-2.1.10-stable.tar.gz解压到当前目录 
3. cd libevent-2.1.10-stable 
4. ./configure 
5. make && make install 
6.在/usr/local/lib目录下 ln -s /usr/local/lib/libevent-2.1.so.6 /usr/lib/libevent-2.1.so.6(为了防止在系统默认路径下 找不到库文件,也可以使用gcc中的-L参数来指定库文件的位置所在)

二、编写测试程序

#include <stdio.h>
#include <stdio.h>  
#include <event.h>
 
void on_time(int sock,short event,void *arg)  
{  
    printf("\r\nhello world\r\n");  
 
 #if 1 //可以中途改变定时时间
    struct timeval tv;  
    tv.tv_sec = 1;  
    tv.tv_usec = 0;  
 
    // 事件执行后,默认就被删除,所以需要重新添加  
    event_add((struct event*)arg, &tv);  
    
#endif

}  

struct timeval lasttime;

void realtime_handle(int sock,short event,void *arg)
{    
    struct timeval newtime, difference;
    struct event *timeout = arg;
    double elapsed;

    printf("\r\n北京欢迎您\r\n"); 
    
    evutil_gettimeofday(&newtime, NULL);
    evutil_timersub(&newtime, &lasttime, &difference);
    elapsed = difference.tv_sec +
        (difference.tv_usec / 1.0e6);

    printf("\ntimeout_cb called at %d': %.3f seconds elapsed.\n",
        (int)newtime.tv_sec, elapsed);
        
    lasttime = newtime;    
}

int main()  
{  
#if 0
    //  初始化事件  
    event_init();  
 
    struct event ev;  
    
    //on_time 回调函数
    evtimer_set(&ev, on_time, &ev);  
 
    //1s运行一次func函数
    struct timeval tv;  
    tv.tv_sec = 1;  
    tv.tv_usec = 0;  
 
    //添加到事件循环中
    event_add(&ev, &tv);  
    
#else 
    struct timeval tv = {2, 0};//定时为10ms
    struct event *timeout = NULL;
    
    struct event_base *base = event_init();  
     
    timeout = event_new(base, -1, EV_PERSIST, realtime_handle,NULL);
    
    evtimer_add(timeout, &tv);
#endif
 
    //程序等待就绪事件并执行事件处理
    event_dispatch();
 
    event_base_free(base);

    return 0;  
}
三、编译 运行验证

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值