1.概述
libubox是OpenWrt中的一个基础库,uloop是libubox中的模块。
uloop中有三个功能:文件描述符触发事件的监控,timeout定时器处理,当前子进程的维护。本文主要介绍其使用方法,不对uloop的源码进行分析。
uloop主要框架
/* 初始化事件循环 */
int uloop_init(void)
/*事件循环处理入口*/
int uloop_run(void)
/* 销毁事件循环 */
int uloop_done(void)
2.使用方法
2.1 文件描述符触发的事件监控
2.1.1 文件描述符uloop结构
struct uloop_fd
{
uloop_fd_handler cb; /*文件描述符对应的回调函数*/
int fd; /* 监听的文件描述符 */
bool eof;
bool error;
bool registered; /* 是否添加到epoll的监控队列 */
uint8_t flags;
};
2.1.2 描述符uloop使用接口
/* 注册一个描述符到事件循环处理 */
int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
/* 从事件处理循环中销毁指定描述符 */
int uloop_fd_delete(struct uloop_fd *sock)
2.1.3 使用实例
static struct uloop_fd ufd;
static void fd_handler(struct uloop_fd *u, unsigned int ev)
{
.....
}
int main(int args, char *argv[])
{
int sockfd = socket(..);
ufd.fd = socket;
ufd.cb = fd_handler;
uloop_init();
uloop_fd_add(&ufd, ULOOP_READ);
uloop_run();
return 0;
}
2.2 定时器事件
2.2.1 定时器timeout结构
struct uloop_timeout
{
struct list_head list; //链表节点
bool pending;
uloop_timeout_handler cb; //回调函数
struct timeval time; //超时时间
}
2.2.2 定时器使用接口
/* 注册定时器 */
int uloop_timeout_add(struct uloop_timeout *timeout);
/* 设置定时器超时时间,并添加 */
int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
/* 销毁指定定时器 */
int uloop_timeout_cancel(struct uloop_timeout *timeout)
/* 定时器还剩多长时间超时 */
int uloop_timeout_remaining(struct uloop_timeout *timeout)
2.2.3 使用实例
static void timeout_handler(struct uloop_timeout *timeout)
{
.....
}
static struct uloop_timeout timer = {
.cb = timeout_handler,
}
int main(int args, char *argv[])
{
uloop_init();
uloop_timeout_set(&timer, 1000); // 1s
uloop_run();
return 0;
}
2.3 进程事件
2.3.1 进程事件处理结构
struct uloop_process
{
struct list_head list;
bool pending;
uloop_process_handler cb; //回调函数
pid_t pid; //文件描述符,调用者初始化
}
2.3.2 进程事件使用接口
/* 注册事件 */
int uloop_process_add(struct uloop_process *p)
/* 销毁 */
int uloop_process_delete(struct uloop_process *p)