四、多路复用-Epoll

4.Epoll

前面讲了poll,还没有解决的两个问题是:

  1. 内核态到用户态的拷贝消耗
  2. 每次都需要遍历都需要o(n)的时间复杂度

4.1 Epoll示意图

那Epoll其实就是用来解决这两个问题的。我们先来看一下Epoll的一个内核示意图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gaHgvSa6-1647085915316)(./picture/4.epoll_create.png)]
四、多路复用-Epoll_第1张图片

当有连接到来时:

四、多路复用-Epoll_第2张图片

4.2 Epoll实例代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXBUF 256

void child_process(void) {
    sleep(2);
    char msg[MAXBUF];
    struct sockaddr_in addr = {0};
    int n, sockfd, num = 1;
    srandom(getpid());
    /* Create socket and connect to server */
    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));    /* Send message */
    }

}

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);
  //上面都是一样的,后面是epoll的逻辑
    struct epoll_event ev[5];
    int epfd = epoll_create(5);
    for (i = 0; i < 5; i++) {
        memset(&client, 0, sizeof(client));
        addrlen = sizeof(client);
      //epoll数组的赋值fd
        ev[i].data.fd = accept(sockfd, (struct sockaddr *) &client, reinterpret_cast<socklen_t *>(&addrlen));
      //赋值event
        ev[i].events = EPOLLIN;
      //设置epoll的端点
        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;
      //读取fd
        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解决的问题

  1. 用户态和内核态都是一份FD数组,所以Epoll解决内核态与用户态拷贝问题
  2. 每次内核会排序,然后把有连接的fd都放到前面,程序中读取就只有O(1)的时间复杂度

你可能感兴趣的:(Linux相关,c语言,udp,网络,多路复用,Epoll)