epoll实现多路IO

  1. 源码地址:https://github.com/whuwzp/linuxc/tree/master/epoll
  2. 源码说明:

1. 概要

int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout); typedef union epoll_data { //联合结构体,占用同一个内存空间,同一时间只有一个有效
void *ptr; //指针,可以指向任何对象,在后面会介绍指向结构体
int fd; //文件描述符
uint32_t u32;
uint64_t u64;
} epoll_data_t; struct epoll_event {
uint32_t events; /* Epoll events */ //监听的事件,如EPOLLIN
epoll_data_t data; /* User data variable */ // 其他数据部分,这个是我们可以设定的,因为epoll_wait返回时会把这个结构体返回到events中,我们就可获取有信号的属性了
};

1.1 epoll_create

epfd = epoll_create(FD_SETSIZE); //返回文件描述符epfd,是红黑树的根节点

1.2 epoll_ctl

//增加节点
evt.data.fd = fd_client;//这里的联合体选择了int fd
evt.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, fd_client, &evt);
//删除节点
epoll_ctl(epfd, EPOLL_CTL_DEL, evts[i].data.fd, nullptr);

增加节点: 是把fd_client文件描述符添加到epfd的红黑树中,同时附带自己的属性,即epoll_event类型的结构体(这个结构体在epoll_wait后会复制到events数组中,这样返回时就可以获取有信号的fd的属性了)

删除节点: 从树中移除

1.3 epoll_wait

nselect = epoll_wait(epfd, evts, FD_SETSIZE, -1);

epfd: 输入,待监听的红黑树

evts: 输出,数组中的元素类型是epoll_event,当fd==n的文件描述符有信号时,会把fd的属性(详见epoll_ctl, 也是epoll_event类型)拷贝到evts中,这样后续我们就可以访问evts[i].data.xxxevts[i].events来获取我们之前设定的数据

1.4 原理

  1. 树中每个节点是fd,每个fd映射着一个epoll_event类型的结构体,像属性一样(epoll_ctl添加节点时自定义的)
  2. epoll_wait监听各个节点,有信号的话,就把它的属性(epoll_event)拷贝到evts中,返回后,就可以通过evts[i].data.xxx得到映射的数据
  3. 如果联合体选择fd, 即evts[i].data.fd,我们就相当于直接获取了fd,可以直接read,write.
  4. 后面的epoll_libevent我们会用ptr指向自定义的结构体

1.5 优势劣势

一定先epoll实现,epoll是poll的改进版,有以下不同:

  1. 结果返回(判断是否有信号)

    • poll:需要轮询数组中的每个元素,看看是不是有信号,用fds[0].revents & POLLIN
    • epoll:一个数组evts专门存放有信号的节点的属性

2. 核心代码

#include "include/wrap.h"
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h> /* See NOTES */
#include <unistd.h>
#include <wait.h>
#define LOCALIP "127.0.0.1"
#define PORT 6666 void handler(char *in, char *out) {
for (int i = 0; i < (int)strlen(out) + 1; ++i) {
out[i] = toupper(in[i]);
}
} int workthread(const int &fd_client) {
char recvbuf[2048] = {0};
char sendbuf[2048] = {0};
int ret = 0; ret = (int)Read(fd_client, recvbuf, 2048);
if (ret <= 0) {
printf("ret==0\n");
return ret;
} handler(recvbuf, sendbuf); ret = (int)Write(fd_client, sendbuf, strlen(sendbuf) + 1);
return ret;
} void startsock(int &fd, struct sockaddr_in &addr, const char *ip,
const int port) {
fd = Socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip);
addr.sin_port = htons(port);
}
int main() {
int fd_server = 0;
int fd_client = 0;
int ret = 0;
struct sockaddr_in sock_client;
struct sockaddr_in sock_server;
socklen_t client_len = (socklen_t)sizeof(sock_client);
int opt = 0;
int epfd = 0;
int nselect = 0;
int i = 0;
struct epoll_event evts[FD_SETSIZE];
struct epoll_event evt;
startsock(fd_server, sock_server, LOCALIP, PORT);
opt = 1;
Setsockopt(fd_server, SOL_SOCKET, SO_REUSEADDR, &opt,
(socklen_t)sizeof(opt));
Bind(fd_server, (struct sockaddr *)&sock_server, sizeof(sock_server));
Listen(fd_server, 5);
epfd = epoll_create(FD_SETSIZE);
if (epfd == -1) { perror_exit("epoll create failed"); } evt.events = EPOLLIN;
evt.data.fd = fd_server;
epoll_ctl(epfd, EPOLL_CTL_ADD, fd_server, &evt); while (true) {
printf("epolling...\n");
nselect = epoll_wait(epfd, evts, FD_SETSIZE, -1);
printf("get %d select\n", nselect);
for (i = 0; i < nselect; ++i) {
if (!(evts[i].events && EPOLLIN)) continue;
if (evts[i].data.fd == fd_server) {//直接拿到fd_server
fd_client = Accept(fd_server, (struct sockaddr *)&sock_client,
&client_len);
printf("accept: %s: %d\n", inet_ntoa(sock_client.sin_addr),
ntohs(sock_client.sin_port));
evt.data.fd = fd_client;
evt.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, fd_client, &evt);
} else {
ret = workthread(evts[i].data.fd);//通过data.fd获取fd
if (ret <= 0) {
Close(evts[i].data.fd);
epoll_ctl(epfd, EPOLL_CTL_DEL, evts[i].data.fd, nullptr);
}
}
}
}
Close(fd_server);
}

3. 参考网址

  1. https://www.bilibili.com/video/av53016117
  2. EPOLLOUT的用处:https://www.zhihu.com/question/22840801 https://github.com/yedf/handy

    write: 不停地写数据,因为EPOLLOUT是只要缓冲区未满,就会有信号

Linux C++ 网络编程学习系列(4)——多路IO之epoll基础的更多相关文章

  1. Linux C++ 网络编程学习系列(1)——端口复用实现

    Linux C++ 网络编程学习系列(1)--端口复用实现 源码地址:https://github.com/whuwzp/linuxc/tree/master/portreuse 源码说明: serv ...

  2. Linux C++ 网络编程学习系列(5)——多路IO之epoll边沿触发

    多路IO之epoll边沿触发+非阻塞 源码地址:https://github.com/whuwzp/linuxc/tree/master/epoll_ET_LT_NOBLOCK_example 源码说 ...

  3. Linux C++ 网络编程学习系列(6)——多路IO之epoll高级用法

    poll实现多路IO 源码地址:https://github.com/whuwzp/linuxc/tree/master/epoll_libevent 源码说明: server.cpp: 监听127. ...

  4. Linux C++ 网络编程学习系列(3)——多路IO之poll实现

    poll实现多路IO 源码地址:https://github.com/whuwzp/linuxc/tree/master/poll 源码说明: server.cpp: 监听127.1:6666,功能是 ...

  5. Linux C++ 网络编程学习系列(2)——多路IO之select实现

    select实现多路IO 源码地址:https://github.com/whuwzp/linuxc/tree/master/select 源码说明: server.cpp: 监听127.1:6666 ...

  6. Linux C++ 网络编程学习系列(7)——mbedtls编译使用

    mbedtls编译使用 环境: Ubuntu18.04 编译器:gcc或clang 编译选项: 静态编译使用 1. mbedtls源码 下载地址: https://github.com/ARMmbed ...

  7. Linux C网络编程学习笔记

    Linux C网络编程总结报告 一.Linux C 网络编程知识介绍: 网络程序和普通的程序有一个最大的区别是网络程序是由两个部分组成的--客户端和服务器端. 客户端:(client) 在网络程序中, ...

  8. linux下网络编程学习——入门实例ZZ

    http://www.cppblog.com/cuijixin/archive/2008/03/14/44480.html 是不是还对用c怎么实现网络编程感到神秘莫测阿,我们这里就要撕开它神秘的面纱, ...

  9. Linux下网络编程学习杂记

    1.TCP/IP协议的体系结构包含四层:应用层(负责应用程序的网络服务,通过端口号识别各个不同的进程)->传输层(传输控制层协议TCP.用户数据报协议UDP.互联网控制消息协议ICMP)-> ...

随机推荐

  1. Jmeter中使用MD5方法

    在现在这家公司做测试的项目有用到鉴权,token的生成方式有使用到md5,具体的请求url和入参就不方便透露,讲一讲使用方法吧! 自带的Jmeter插件中是没有这个md5的所以,我们可以 (1)打开选 ...

  2. SQL的分类使用(增删改查)

    1.SQL的分类使用(*代表重点的程度)    DDL ** (Data Definition Language)数据库定义语言        用来定义数据库对象: 库 表 列 等    DCL (D ...

  3. python之路---装饰器函数

    阅读目录 楔子 装饰器的形成过程 开放封闭原则 谈装饰器主要功能和装饰器固定结构 带参数的装饰器 多个装饰器装饰一个函数 返回顶部 楔子 作为一个会写函数的python开发,我们从今天开始要去公司上班 ...

  4. C语言结构体实现类似C++的构造函数

    其主要依靠函数指针来实现,具体看代码吧~ #include <stdio.h> #include <stdlib.h> #include <string.h> ty ...

  5. idea的ktorm框架代码生成器插件

    *:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...

  6. Building Applications with Force.com and VisualForce (DEV401) (二二):Visualforce Componets (Tags) Library Part II

    Dev401-023:Visualforce Pages: Visualforce Componets (Tags) Library Part II   Apex:pageBlockTable1.A ...

  7. PHP7内核:源码分析的环境与工具

    本文主要介绍分析源码的方式,其中包含环境的搭建.分析工具的安装以及源码调试的基本操作. 一.工具清单 PHP7.0.12 GDB CLion 二.源码下载及安装 $ wget http://php.n ...

  8. SublimeのJedi (自动补全)

    关于 Sublime 3 - Jedi Package 的设置和使用方法 我是一枚小白,安装后 Sublime 后,想在码字时,达到如下效果: 打字时,自动提示相关内容 按Tab键,相关内容自动填充 ...

  9. [React]Context机制

    在React中,Context机制是为了方便在组件树间传递数据. 例子 import React from 'react' const themes={ light:"亮色主题", ...

  10. linux service 例子

    在 /etc/init.d/ 中创建新文件 #/bin/sh # 检查第一个参数是什么来执行对应动作 case $1 in start) /usr/local/php/bin/php-cgi -b 1 ...