Linux----IO框架库libevent的使用(永久事件及非永久性事件的实现)
iolib.c
执行此程序时命令为:gcc -o iolib iolib.c -levent
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <unistd.h>
#include <event.h>
#include <stdlib.h>
//libevent库的使用
void sig_cb(int fd, short ev, void *arg)
{
printf("fd = %d\n", fd);
}
void timeout_cb(int fd, short ev, void *arg)
{
printf("time out\n");
}
int main()
{
struct event_base *base = event_init();
assert(base != NULL);
//struct event *sig_ev = event_new(base, SIGINT, sig_cb, NULL);非永久性事件
struct event *sig_ev = event_new(base, SIGINT, EV_SIGNAL|EV_PERSIST, sig_cb, NULL); //永久性事件,可以持续获取键盘数据
assert(sig_cb != NULL);
event_add(sig_ev, NULL);
struct timeval tv = {3, 0};//超时时间
//struct event *time_ev = event_new(base, timeout_cb, NULL); //非永久性事件
struct event *time_ev = event_new(base, -1, EV_TIMEOUT|EV_PERSIST, timeout_cb, NULL); //永久性事件,可以持续打印time out
event_add(time_ev, &tv);
event_base_dispatch(base); //启动事件循环的方法
event_free(time_ev);
event_free(sig_ev);
event_base_free(base);
}
结果显示: