Chinaunix首页 | 论坛 | 博客
  • 博客访问: 391200
  • 博文数量: 87
  • 博客积分: 2571
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-29 13:10
文章分类

全部博文(87)

文章存档

2012年(49)

2011年(7)

2010年(26)

2009年(5)

分类: LINUX

2010-04-19 15:27:00

    第一次接触libevent,做个记录备用。
 
 
    libevent
       一个支持Windowslinuxbsd等平台的网络事件驱动程序库。它支持多种I/O服用机制,按照优先级从高到低依次为:evportkqueueepolldevpollrtsigpollselect。它可根据操作系统,按照优先级从高到底自主选择驱动。
 
 
 
    使用
    
   

/*

 * libevent自带的例子,因为不考虑在windows平台下使用,删去了一点跨平台的内容
 * Compile with:
 * cc -I/usr/local/include -o signal-test signal-test.c -L/usr/local/lib -levent
 */


#include <sys/types.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <sys/stat.h>
#include <sys/queue.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <event.h>

int called = 0;

static void
signal_cb(int fd, short event, void *arg)
{
    struct event *signal = arg;

    printf("%s: got signal %d\n", __func__, EVENT_SIGNAL(signal));

    if (called >= 2)
        event_del(signal);//事件删除    
    called++;
}

int
main (int argc, char **argv)
{
    struct event signal_int;
 
    /* Initalize the event library */
    event_init();//初始化

    //可有 event_base main_base = event_init();

    //另外,有专用于http、dns、rpc等的初始化函数

    /* Initalize one event */
    event_set(&signal_int, SIGINT, EV_SIGNAL|EV_PERSIST, signal_cb,
     &signal_int);//设置事件

    //事件类型包括EV_READ、EV_WRITE、EV_PERSIST等

    //另外有一个设置时间的函数evtimer_set(...);

    event_add(&signal_int, NULL);//加入事件队列

    //第二个参数为超时值,可以为空

    event_dispatch();//启动事件循环

    //另一种常用方式为event_base_loop(event_base类型变量/*event_base的返回值*/,0)

    return (0);
}


阅读(2765) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~