一、简介
Libevent 是一个用C语言编写的、轻量级的开源高性能网络库,主要特点:
1、事件驱动,即异步调用
2、支持多种 I/O多路复用技术, epoll、poll、dev/poll、select 和kqueue 等。
地址在 http://libevent.org/ 可在该网站下载最新的代码库。
The libevent API provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. Furthermore, libevent also support callbacks due to signals or regular timeouts.
二、安装
下载libevent-1.4.14b-stable.tar.gz,执行以下操作
tar –xzvf libevent-1.4.14b-stable.tar.gz
cd libevent-1.4.14b-stable
./configure --prefix=/usr/local/libevent
make
make install
root@ubuntu:memcached# whereis libevent
libevent: /usr/local/libevent
三、使用
1、简单的定时器程序
1 #include <iostream> 2 #include <event.h> 3 #include <stdio.h> 4 5 using namespace std; 6 7 struct event timer; 8 struct timeval tv; 9 static char data[0x100] = "hello, mamoyang! "; 10 11 void say_hello(int fd, short event, void* arg) 12 { 13 printf("%d, %d, %s", fd, event, (char* )arg); 14 evtimer_add(&timer, &tv); 15 } 16 17 int main(void) 18 { 19 event_init(); 20 evtimer_set(&timer, say_hello, data); 21 tv.tv_sec = 2; 22 tv.tv_usec = 0; 23 evtimer_add(&timer, &tv); 24 25 event_dispatch(); 26 return 0; 27 }
Makefile如下:
1 TARG=timer 2 3 all: $(TARG) 4 5 CFLAGS= -g -O0 -I /usr/local/libevent/include 6 LDFLAGS= -L /usr/local/libevent/lib -levent 7 8 9 $(TARG) : $(TARG).cpp 10 g++ $(CFLAGS) $< -o $@ $(LDFLAGS) 11 12 clean: 13 rm -rf $(TARG)
root@ubuntu:timer# ./timer
-1, 1, hello, mamoyang!
-1, 1, hello, mamoyang!