本文主要是介绍linux epoll反应堆模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
epoll反应堆模型的流程:
epoll_create(); // 创建监听红黑树
epoll_ctl(); // 向书上添加监听fd
epoll_wait(); // 监听
有客户端连接上来--->lfd调用acceptconn()--->将新创建的通信套接字的文件描述符cfd挂载到红黑树上监听读事件--->
epoll_wait()返回--->cfd回调recvdata()--->将cfd摘下来监听写事件(TCP的滑动窗口机制,监听一下是否能向客户端写数据过去)--->
epoll_wait()返回--->cfd回调senddata()--->将cfd摘下来监听读事件--->...--->
核心就是下面这张图!!!!!,这是理解整个代码的关键。
注意,挂到红黑树的每一个结点的类型都是struct epoll_event
类型的。
server.c
/**epoll基于非阻塞I/O事件驱动*/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>#define MAX_EVENTS 1024 //监听上限数
#define BUFLEN 4096
#define SERV_PORT 6666void recvdata(int fd, void *arg);
void senddata(int fd, void *arg);/* 描述就绪文件描述符相关信息 */struct myevent_s {int fd; //要监听的文件描述符int events; //对应的监听事件void *arg; //泛型参数void (*call_back)(int fd,void *arg); //回调函数int status; //是否在监听:1->在红黑树上(监听), 0->不在(不监听)char buf[BUFLEN];int len;long last_active; //记录每次加入红黑树 g_efd 的时间值
};int g_efd; //全局变量, 保存epoll_create返回的文件描述符
struct myevent_s g_events[MAX_EVENTS+1]; //自定义结构体类型数组. +1-->listen fd/*将结构体 myevent_s 成员变量 初始化*/void eventset(struct myevent_s *my_ev, int fd, void (*call_back)(int, int, void *), void *arg)
{my_ev->fd = fd;my_ev->call_back = call_back;my_ev->events = 0;my_ev->arg = arg;my_ev->status = 0;//memset(my_ev->buf, 0, sizeof(my_ev->buf));//my_ev->len = 0;my_ev->last_active = time(NULL); //调用eventset函数的时间return;
}/* 向 epoll监听的红黑树 添加一个文件描述符 */void eventadd(int efd, int events, struct myevent_s *my_ev)
{struct epoll_event epv = {0, {0}};int op;epv.data.ptr = my_ev;epv.events = my_ev->events = events; //EPOLLIN 或 EPOLLOUTif (my_ev->status == 1) { //已经在红黑树 g_efd 里op = EPOLL_CTL_MOD; //修改其属性} else { //不在红黑树里op = EPOLL_CTL_ADD; //将其加入红黑树 g_efd, 并将status置1my_ev->status = 1;}if (epoll_ctl(efd, op, my_ev->fd, &epv) < 0) //实际添加/修改printf("event add failed [fd=%d], events[%d]\n", my_ev->fd, events);elseprintf("event add OK [fd=%d], op=%d, events[%0X]\n", my_ev->fd, op, events);return ;
}/* 从epoll 监听的 红黑树中删除一个 文件描述符*/void eventdel(int efd, struct myevent_s *my_ev)
{//struct epoll_event epv = {0, {0}};if (my_ev->status != 1) //不在红黑树上return ;//epv.data.ptr = my_ev;my_ev->status = 0; //修改状态//epoll_ctl(efd, EPOLL_CTL_DEL, my_ev->fd, &epv); //从红黑树 efd 上将 my_ev->fd 摘除epoll_ctl(efd, EPOLL_CTL_DEL, my_ev->fd, NULL); return ;
}/* 当有文件描述符就绪, epoll返回, 调用该函数 与客户端建立链接 */void acceptconn(int lfd,void *arg)
{struct sockaddr_in cin;socklen_t len = sizeof(cin);int cfd, i;if ((cfd = accept(lfd, (struct sockaddr *)&cin, &len)) == -1) {if (errno != EAGAIN && errno != EINTR) {/* 暂时不做出错处理 */}printf("%s: accept, %s\n", __func__, strerror(errno));return ;}do {for (i = 0; i < MAX_EVENTS; i++) //从全局数组g_events中找一个空闲元素if (g_events[i].status == 0) //类似于select中找值为-1的元素break; //跳出 forif (i == MAX_EVENTS) {printf("%s: max connect limit[%d]\n", __func__, MAX_EVENTS);break; //跳出do while(0) 不执行后续代码}int flag = 0;if ((flag = fcntl(cfd, F_SETFL, O_NONBLOCK)) < 0) { //将cfd也设置为非阻塞printf("%s: fcntl nonblocking failed, %s\n", __func__, strerror(errno));break;}/* 给cfd设置一个 myevent_s 结构体, 回调函数 设置为 recvdata */eventset(&g_events[i], cfd, recvdata, &g_events[i]); eventadd(g_efd, EPOLLIN, &g_events[i]); //将cfd添加到红黑树g_efd中,监听读事件} while(0);printf("new connect [%s:%d][time:%ld], pos[%d]\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), g_events[i].last_active, i);return ;
}void recvdata(int fd,void *arg)
{struct myevent_s *my_ev = (struct myevent_s *)arg;int len;len = recv(fd, my_ev->buf, sizeof(my_ev->buf), 0); //读文件描述符, 数据存入myevent_s成员buf中eventdel(g_efd, my_ev); //将该节点从红黑树上摘除if (len > 0) {my_ev->len = len;my_ev->buf[len] = '\0'; //手动添加字符串结束标记printf("C[%d]:%s\n", fd, my_ev->buf);eventset(my_ev, fd, senddata, my_ev); //设置该 fd 对应的回调函数为 senddataeventadd(g_efd, EPOLLOUT, my_ev); //将fd加入红黑树g_efd中,监听其写事件} else if (len == 0) {close(my_ev->fd);/* my_ev-g_events 地址相减得到偏移元素位置 */printf("[fd=%d] pos[%ld], closed\n", fd, my_ev-g_events);} else {close(my_ev->fd);printf("recv[fd=%d] error[%d]:%s\n", fd, errno, strerror(errno));}return;
}void senddata(int fd,void *arg)
{struct myevent_s *my_ev = (struct myevent_s *)arg;int len;len = send(fd, my_ev->buf, my_ev->len, 0); //直接将数据 回写给客户端。未作处理/*printf("fd=%d\tev->buf=%s\ttev->len=%d\n", fd, my_ev->buf, my_ev->len);printf("send len = %d\n", len);*/if (len > 0) {printf("send[fd=%d], [%d]%s\n", fd, len, my_ev->buf);eventdel(g_efd, my_ev); //从红黑树g_efd中移除eventset(my_ev, fd, recvdata, my_ev); //将该fd的 回调函数改为 recvdataeventadd(g_efd, EPOLLIN, my_ev); //从新添加到红黑树上, 设为监听读事件} else {close(my_ev->fd); //关闭链接eventdel(g_efd, my_ev); //从红黑树g_efd中移除printf("send[fd=%d] error %s\n", fd, strerror(errno));}return ;
}/*创建 socket, 初始化lfd */void initlistensocket(int efd, short port)
{int lfd = socket(AF_INET, SOCK_STREAM, 0);fcntl(lfd, F_SETFL, O_NONBLOCK); //将socket设为非阻塞/* void eventset(struct myevent_s *my_ev, int fd, void (*call_back)(int, int, void *), void *arg); */eventset(&g_events[MAX_EVENTS], lfd, acceptconn, &g_events[MAX_EVENTS]);//放到g_events数组的最后一个位置上/* void eventadd(int efd, int events, struct myevent_s *my_ev) */eventadd(efd, EPOLLIN, &g_events[MAX_EVENTS]);struct sockaddr_in sin;memset(&sin, 0, sizeof(sin)); //bzero(&sin, sizeof(sin))sin.sin_family = AF_INET;sin.sin_addr.s_addr = INADDR_ANY;sin.sin_port = htons(port);bind(lfd, (struct sockaddr *)&sin, sizeof(sin));listen(lfd, 20);return ;
}int main(int argc, char *argv[])
{unsigned short port = SERV_PORT;if (argc == 2)port = atoi(argv[1]); //使用用户指定端口.如未指定,用默认端口g_efd = epoll_create(MAX_EVENTS+1); //创建红黑树,返回给全局 g_efd if (g_efd <= 0)printf("create efd in %s err %s\n", __func__, strerror(errno));initlistensocket(g_efd, port); //初始化监听socketstruct epoll_event events[MAX_EVENTS+1]; //保存已经满足就绪事件的文件描述符数组 printf("server running:port[%d]\n", port);int checkpos = 0, i;while (1) {/* 超时验证,每次测试100个链接,不测试listenfd 当客户端60秒内没有和服务器通信,则关闭此客户端链接 */long now = time(NULL); //当前时间for (i = 0; i < 100; i++, checkpos++) { //一次循环检测100个。 使用checkpos控制检测对象if (checkpos == MAX_EVENTS)checkpos = 0;if (g_events[checkpos].status != 1) //不在红黑树 g_efd 上continue;long duration = now - g_events[checkpos].last_active; //客户端不活跃的时间if (duration >= 60) {close(g_events[checkpos].fd); //关闭与该客户端链接printf("[fd=%d] timeout\n", g_events[checkpos].fd);eventdel(g_efd, &g_events[checkpos]); //将该客户端 从红黑树 g_efd移除}}/*监听红黑树g_efd, 将满足的事件的文件描述符加至events数组中, 1秒没有事件满足, 返回 0*/int nfd = epoll_wait(g_efd, events, MAX_EVENTS+1, 1000);if (nfd < 0) {printf("epoll_wait error, exit\n");break;}for (i = 0; i < nfd; i++) {/*使用自定义结构体myevent_s类型指针, 接收 联合体data的void *ptr成员*/struct myevent_s *my_ev = (struct myevent_s *)events[i].data.ptr; if ((events[i].events & EPOLLIN) && (my_ev->events & EPOLLIN)) { //读就绪事件my_ev->call_back(my_ev->fd, my_ev->arg);}if ((events[i].events & EPOLLOUT) && (my_ev->events & EPOLLOUT)) { //写就绪事件my_ev->call_back(my_ev->fd, my_ev->arg);}}}/* 退出前释放所有资源 */return 0;
}
这篇关于linux epoll反应堆模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!