针对epoll api的两种触发模式,lt和et,仿照一些例子写了代码进行实验。
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/epoll.h> #include <pthread.h> #include <assert.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #define MAX_EVENT_NUMBER 1024 #define BUFFER_SIZE 10 int setnonblocking(int fd) { int old_option = fcntl(fd, F_GETFL); int new_option = old_option | O_NONBLOCK; fcntl(fd, F_SETFL, new_option); return old_option; } void addfd(int epollfd, int fd, bool enable_et) { epoll_event event; event.data.fd = fd; event.events = EPOLLIN; if (enable_et) { event.events |= EPOLLET; } epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); setnonblocking(fd); } void lt(epoll_event *events, int number, int epollfd, int listenfd) { char buf[BUFFER_SIZE]; for (int i=0; i<number; i++) { int sockfd = events[i].data.fd; if (sockfd == listenfd) { sockaddr_in client_address; socklen_t client_addrlen = sizeof(client_address); int connfd = accept(listenfd, (sockaddr*)&client_address, &client_addrlen); addfd(epollfd, connfd, false); } else if (events[i].events & EPOLLIN) { printf("lt event trigger once "); memset(buf, '