在前面的文章中曾经粗略讲过poll,那时是用阻塞IO实现,在发送和接收数据量都较小情况下和网络状况良好的情况下是基本没有问题的,read 不会只接收部分数据,write 也不会一直阻塞。但实际上poll IO复用经常是跟非阻塞IO一起使用的,想想如果现在内核接收缓冲区一点数据没有,read 阻塞了,或者内核发送缓冲区不够空间存放数据,write 阻塞了,那整个事件循环就会延迟响应,比如现在又有一个新连接connect上来了,也不能很快回到循环去accept 它。
在前面的文章中也曾粗略讲过epoll,使用的是ET 边沿触发模式,每次accept 返回需要将conn 设置为非阻塞,ET模式可能存在的问题是有可能只读取了部分数据,剩下的epoll_wait 就再也不会返回可读事件了。
这篇文章来谈谈如何正确使用non-blocking I/O Multiplexing + poll/epoll。
1、首先来回顾下poll / epoll 函数的原型
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
#include <sys/epoll.h>
int epoll_create(int size); //size 并不代表能够容纳的事件个数
int epoll_create1(int flags); // EPOLL_CLOEXEC
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct epoll_event {
uint32_t events; /* Epoll events */
int epoll_create(int size); //size 并不代表能够容纳的事件个数
int epoll_create1(int flags); // EPOLL_CLOEXEC
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct epoll_event {
uint32_t events; /* Epoll events */