一、epoll 系列函数简介
#include <sys/epoll.h>
int epoll_create(int size);
int epoll_create1(int flags);
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);
* epoll_create(2) creates an epoll instance and returns a file descriptor referring to that instance. (The more recent
epoll_create1(2) extends the functionality of epoll_create(2).)
* Interest in particular file descriptors is then registered via epoll_ctl(2). The set of file descriptors currently
registered on an epoll instance is sometimes called an epoll set.
* epoll_wait(2) waits for I/O events, blocking the calling thread if no events are currently available.
1、epoll_create1 产生一个epoll 实例,返回的是实例的句柄。flag 可以设置为0 或者EPOLL_CLOEXEC,为0时函数表现与epoll_create一致,EPOLL_CLOEXEC标志与open 时的O_CLOEXEC 标志类似,即进程被替换时会关闭打开的文件描述符。
2、epoll_ctl :
(1)epfd:epoll 实例句柄;
(2)op:对文件描述符fd 的操作,主要有EPOLL_CTL_ADD、 EPOLL_CTL_DEL等;
(3)fd:需要操作的目标文件描述符;
(4)event:结构体指针
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 */
epoll_data_t data; /* User data variable */
};
events 参数主要有EPOLLIN、EPOLLOUT、EPOLLET、EPOLLLT等;一般data 共同体我们设置其成员fd即可,也就是epoll_ctl 函数的第三个参数。
3、epoll_wait:
(1)epfd:epoll 实例句柄;
(2)events:结构体指针
(3)maxevents:事件的最大个数
(4)timeout:超时时间,设为-1表示永不超时
下面我们使用c++ 来实现一个服务器端程序:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |