工作原理分析
- 水平触发(LT):只要文件描述符对应的缓冲区还有未读数据或者还有可写入空间,epoll_wait就会不断通知应用程序。应用程序可以不一次把数据读完或写完,下次epoll_wait仍会通知。
- 边缘触发(ET):只有在文件描述符状态发生变化时(如从无数据到有数据,从不可写到可写),epoll_wait才会通知应用程序。一旦通知,应用程序必须尽可能多地读写数据,直到达到EWOULDBLOCK错误,否则可能会丢失后续数据。
ET模式下关键要点
- 非阻塞I/O:必须将文件描述符设置为非阻塞模式,因为ET模式下只通知一次,若使用阻塞I/O,可能在处理当前事件时阻塞,错过后续事件通知。
- 数据读取:在收到事件通知后,要循环读取数据,直到read返回 -1且errno为EWOULDBLOCK,确保将缓冲区数据读完。
- 数据写入:同样,在处理写事件时,要循环写入数据,直到write返回 -1且errno为EWOULDBLOCK,确保将数据全部写入。
示例代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <fcntl.h>
#define MAX_EVENTS 10
#define BUF_SIZE 1024
void setnonblocking(int sockfd) {
int opts;
opts = fcntl(sockfd, F_GETFL);
if (opts < 0) {
perror("fcntl(F_GETFL)");
exit(1);
}
opts = opts | O_NONBLOCK;
if (fcntl(sockfd, F_SETFL, opts) < 0) {
perror("fcntl(F_SETFL)");
exit(1);
}
}
int main(int argc, char *argv[]) {
int listen_sock, conn_sock;
struct sockaddr_in servaddr, cliaddr;
socklen_t clilen = sizeof(cliaddr);
struct epoll_event ev, events[MAX_EVENTS];
int epollfd;
char buf[BUF_SIZE];
listen_sock = socket(AF_INET, SOCK_STREAM, 0);
if (listen_sock < 0) {
perror("socket");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
bzero(&cliaddr, sizeof(cliaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(atoi(argv[1]));
if (bind(listen_sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind");
close(listen_sock);
exit(1);
}
if (listen(listen_sock, 5) < 0) {
perror("listen");
close(listen_sock);
exit(1);
}
epollfd = epoll_create1(0);
if (epollfd == -1) {
perror("epoll_create1");
close(listen_sock);
exit(1);
}
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = listen_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) {
perror("epoll_ctl: listen_sock");
close(listen_sock);
close(epollfd);
exit(1);
}
for (;;) {
int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (nfds == -1) {
perror("epoll_wait");
break;
}
for (int n = 0; n < nfds; ++n) {
if (events[n].data.fd == listen_sock) {
conn_sock = accept(listen_sock, (struct sockaddr *)&cliaddr, &clilen);
if (conn_sock == -1) {
perror("accept");
continue;
}
setnonblocking(conn_sock);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = conn_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1) {
perror("epoll_ctl: conn_sock");
close(conn_sock);
}
} else {
conn_sock = events[n].data.fd;
int ret;
while ((ret = read(conn_sock, buf, sizeof(buf))) > 0) {
write(STDOUT_FILENO, buf, ret);
}
if (ret == -1 && errno != EWOULDBLOCK) {
perror("read");
close(conn_sock);
if (epoll_ctl(epollfd, EPOLL_CTL_DEL, conn_sock, NULL) == -1) {
perror("epoll_ctl: del conn_sock");
}
}
}
}
}
close(listen_sock);
close(epollfd);
return 0;
}