4.Epoll
前面讲了poll,还没有解决的两个问题是:
- 内核态到用户态的拷贝消耗
- 每次都需要遍历都需要o(n)的时间复杂度
4.1 Epoll示意图
那Epoll其实就是用来解决这两个问题的。我们先来看一下Epoll的一个内核示意图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gaHgvSa6-1647085915316)(./picture/4.epoll_create.png)]
当有连接到来时:
4.2 Epoll实例代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <wait.h>
#include <signal.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <sys/poll.h>
#include <sys/epoll.h>
#define MAXBUF 256
void child_process(void) {
sleep(2);
char msg[MAXBUF];
struct sockaddr_in addr = {0};
int n, sockfd, num = 1;
srandom(getpid());
sockfd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(2000);
addr.sin_addr.s_addr = 16777343;
connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
printf("child {%d} connected \n", getpid());
while (1) {
int sl = (random() % 10) + 1;
num++;
sleep(sl);
sprintf(msg, "Test message %d from client %d", num, getpid());
n = write(sockfd, msg, strlen(msg));
}
}
int main() {
char buffer[MAXBUF];
int fds[5];
struct sockaddr_in addr;
struct sockaddr_in client;
int addrlen, n, i, max = 0;;
int sockfd, commfd;
for (i = 0; i < 5; i++) {
if (fork() == 0) {
child_process();
exit(0);
}
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(2000);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
listen(sockfd, 5);
struct epoll_event ev[5];
int epfd = epoll_create(5);
for (i = 0; i < 5; i++) {
memset(&client, 0, sizeof(client));
addrlen = sizeof(client);
ev[i].data.fd = accept(sockfd, (struct sockaddr *) &client, reinterpret_cast<socklen_t *>(&addrlen));
ev[i].events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, ev[i].data.fd, ev);
}
while (1) {
puts("round again");
nfds_t nfds = epoll_wait(epfd, ev, 5, 1000);
int i = 0;
for (i = 0; i < nfds; i++) {
memset(buffer, 0, MAXBUF);
read(ev[i].data.fd, buffer, MAXBUF);
puts("round again111");
puts(buffer);
}
}
return 0;
}
4.3 Epoll解决的问题
- 用户态和内核态都是一份FD数组,所以Epoll解决内核态与用户态拷贝问题
- 每次内核会排序,然后把有连接的fd都放到前面,程序中读取就只有O(1)的时间复杂度
|