当前位置:网站首页>Socket programming -- epoll model
Socket programming -- epoll model
2022-06-25 08:56:00 【Programming segment】
utilize epoll The model implements multiple clients and one server CS Model —— multiple IO Multiplexing technology
【 Last one 】:poll Model
【 Read before reading 】:epoll Detailed explanation
epoll advantage
- select and poll Is linear processing , and epoll It's red and black tree treatment
- select and poll Copy frequently in the kernel and user area , and epoll Using shared memory
- The program needs to select and poll Only by judging the returned set can we know which file descriptors are ready , but epoll You can directly get the set of ready file descriptors , There is no need to test again
- epoll
Delegate the detection of changes in file descriptors to the kernel , Then the kernel returns the event corresponding to the changed descriptor to the program . Not only tell the program that there are several changes , And tell the program exactly which ones have changed
Create a tree epoll Trees
int epoll_create(int size);
param:
size: Maximum number of nodes , Need to pass greater than 0 Number of numbers ,linux This parameter is ignored on
return:
success : Return is greater than the 0 File descriptor for , Represents the root of the whole tree
Failure : return -1
The node to listen to is in epoll Add... To the tree 、 Delete and modify
int epoll_ctl(int epfd, int op, int fd, struct epoll_event* event);
param:
epfd:epoll_create The return value of the function
op: EPOLL_CTL_ADD: Go to epoll Add a new node to the model
EPOLL_CTL_MOD: modify epoll Nodes that already exist in the model
EPOLL_CTL_DEL: Delete epoll Specified nodes in the model
fd: File descriptor to operate on
event: What events are detected for this file descriptor
event.events: entrust epoll Detected events
EPOLLIN: Read events , receive data , Detect read buffer
EPOLLOUT: Write events , send data , Detect write buffer
EPOLLERR: Unusual events
event.data: Usually use the inside fd member , File descriptors that delegate kernel monitoring , Calling epoll_wait This value will be passed out when the function is called
return:
success : return 0
Failure : return - 1
Delegate kernel monitoring epoll Is there a ready file descriptor in the instance
int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);
param:
epfd: epoll_create The return value of the function , Find... Through this parameter epoll example
events: Out parameter , It stores the information of the ready file descriptor
maxevents: Modify the second parameter , The capacity of the structure array ( Element number )
timeout: 0: Function does not block
>0: The function blocks the corresponding number of milliseconds and returns
-1: The function has been blocked , until epoll Unblock only after there are ready file descriptors in the instance
The server code is as follows , The client code remains unchanged
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netinet/in.h>
#include<errno.h>
#include<sys/epoll.h>
int main()
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd < 0)
{
perror("socket error");
return -1;
}
struct sockaddr_in serv;
bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret < 0)
{
perror("bind error");
return -1;
}
listen(lfd, 128);
// Create a tree epoll Trees
struct epoll_event ev;
struct epoll_event events[1024];
int epfd = epoll_create(1024);
if(epfd < 0)
{
perror("create epoll error");
return -1;
}
// Will listen to the file descriptor on the tree
ev.data.fd = lfd;
ev.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
int nready;
int max=0;// Indicates the scope of kernel monitoring , In the beginning 1 individual
int cfd;
int sockfd;
int i;
int n;
char buf[1024];
while(1)
{
nready = epoll_wait(epfd, events, 1024, -1);
if(nready < 0)
{
if(errno == EINTR)
continue;
perror("epoll wait error\n");
break;
}
for(i=0; i<nready; i++)
{
// There is a client connection request coming
sockfd = events[i].data.fd;
if(sockfd == lfd)
{
cfd = accept(lfd, NULL, NULL);
// New cfd Up a tree
ev.data.fd = cfd;
ev.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
continue;
}
// Some data has been sent
memset(buf, 0, sizeof(buf));
//n = read(sockfd, buf, sizeof(buf));
n = recv(sockfd, buf, sizeof(buf), 0);
if(n <= 0)
{
close(sockfd);
// take sockfd The node of the corresponding event is from epoll Delete... From the tree
epoll_ctl(epfd, EPOLL_CTL_DEL, sockfd, NULL);
printf("read error or client close\n");
continue;
}
printf("n == [%d], buf == [%s]\n", n, buf);
for(int j=0; j<n; j++)
{
buf[j] = toupper(buf[j]);
}
//write(sockfd, buf, n);
send(sockfd, buf, n, 0); }
}
close(epfd);
close(lfd);
return 0;
}
Expand :
epoll Of ET( edge-triggered ) and LT( Level trigger ) Pattern
- epoll By default LT Pattern , In this mode , If the data is not read at one time , The buffer also has readable data , be epoll_wait Will also inform ( Like hair 10 Data , Once read only twice , Then it will read circularly 5 Time )
- If the epoll Set to ET Pattern (ev.events = EPOLLIN | EPOLLET), If the data is not read at one time , be epoll_wait No more notice , Until the next time new data is sent ( It also reads the data received by the last buffer but not yet read out )
边栏推荐
- Advanced technology Er, meet internship position information
- Check whether the point is within the polygon
- Lvs-dr mode multi segment case
- Cazy eight trigrams maze of Chang'an campaign
- 二、训练fashion_mnist数据集
- Notes on key words in the original English work biography of jobs (VI) [chapter three]
- What does openid mean? What does "token" mean?
- Openfoam: bottom layer
- 浏览器查看当前页面所有的监听事件
- 城链科技平台,正在实现真正意义上的价值互联网重构!
猜你喜欢

matplotlib 简单逻辑回归可视化

How can games copied from other people's libraries be displayed in their own libraries
![[operation tutorial] how does the tsingsee Qingxi video platform import the old database into the new database?](/img/21/08194ac26dec50c222b88f1f64f894.png)
[operation tutorial] how does the tsingsee Qingxi video platform import the old database into the new database?

五、项目实战---识别人和马

Cazy eight trigrams maze of Chang'an campaign

备战2022年金九银十必问的1000道Android面试题及答案整理,彻底解决面试的烦恼

Oracle one line function Encyclopedia

浏览器查看当前页面所有的监听事件

【无标题】**数据库课设:三天完成学生信息管理系统**

检测点是否在多边形内
随机推荐
《乔布斯传》英文原著重点词汇笔记(六)【 chapter three 】
华泰证券在上面开股票账户安全吗?
[MySQL] understanding of transactions
《乔布斯传》英文原著重点词汇笔记(三)【 chapter one】
What is the file that tp6 automatically executes? What does the tp6 core class library do?
Is it safe to buy stocks and open accounts through the account QR code of the account manager? Want to open an account for stock trading
关于I/O——内存与CPU与磁盘之间的关系
RTOS 多线程下hardfault问题总结
【总结】1361- package.json 与 package-lock.json 的关系
compiling stm32f4xx_it.c... “.\Objects\BH-F407.axf“ - 42 Error(s), 1 Warning(s).
城鏈科技平臺,正在實現真正意義上的價值互聯網重構!
Openfoam: bottom layer
Lvs-dr mode multi segment case
C language: count the number of words in a paragraph
How to increase the monthly salary of software testing from 10K to 30K? Only automated testing can do it
C # startup program loses double quotation marks for parameters passed. How to solve it?
WebGL谷歌提示内存不够(RuntimeError:memory access out of bounds,火狐提示索引超出界限(RuntimeError:index out of bounds)
The city chain technology platform is realizing the real value Internet reconstruction!
sklearn 高维数据集制作make_circles 和 make_moons
Chinese solution cannot be entered after webgl is published