TCP/IP网络编程 -- (十七)由于select的epoll
select 的优点:大多数操作系统都支持
epoll 优点:内部的 epoll 空间是由红黑树构成,而 select 与 poll 都是线性表,发生事件时不需要遍历所有文件描述符,可以直接找到发生事件的集合
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 */
} __EPOLL_PACKED;
上述为描述事件信息的结构体,其中联合体 data 一般只用 fd 作为文件描述符即可,因为在等待事件函数 epoll_wait 函数中作为传出参数,把发生事件的集合传入 __events 数组中
extern int epoll_wait (int __epfd, struct epoll_event *__events,
int __maxevents, int __timeout);
通过 events[i].data.fd 拿到发生事件的文件描述符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#define BUF_SIZE 100
#define EPOLL_SIZE 50
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
socklen_t adr_sz;
int str_len;
char buf[BUF_SIZE];
struct epoll_event *ep_events;
struct epoll_event event;
int epfd, event_cnt;
if (argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if (bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
error_handling("bind() error");
if (listen(serv_sock, 5) == -1)
error_handling("listen() error");
epfd = epoll_create(EPOLL_SIZE);
ep_events = malloc(sizeof(struct epoll_event)*EPOLL_SIZE);
//监听连接请求
event.events = EPOLLIN;
event.data.fd = serv_sock;
epoll_ctl(epfd, EPOLL_CTL_ADD, serv_sock, &event);
while(1)
{
event_cnt = epoll_wait(epfd, ep_events, EPOLL_SIZE, -1);
if (event_cnt == -1)
{
puts("epoll_wait() error");
break;
}
for (int i = 0; i < event_cnt; i++)
{
//有新的连接请求
if (ep_events[i].data.fd == serv_sock)
{
adr_sz = sizeof(clnt_adr);
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz);
event.events = EPOLLIN;
event.data.fd = clnt_sock;
epoll_ctl(epfd, EPOLL_CTL_ADD, clnt_sock, &event);
printf("connected client %d \n", clnt_sock);
}
//有通信内容
else
{
str_len = read(ep_events[i].data.fd, buf, BUF_SIZE);
//连接关闭
if (str_len == 0)
{
epoll_ctl(epfd, EPOLL_CTL_DEL, ep_events[i].data.fd, NULL);
close(ep_events[i].data.fd);
printf("closed client: %d \n", ep_events[i].data.fd);
}
else
{
write(ep_events[i].data.fd, buf, str_len);
}
}
}
}
close(serv_sock);
close(epfd);
return 0;
}
可在注册事件时加入|IEPOLLET 使其变为边缘触发
event.events = EPOLLIN|IEPOLLET;
默认的条件出发是只要缓冲区有数据都会触发;
边缘触发是只有缓冲区被输入数据时才触发,这些数据之后如果被分批次读取时不会触发
好处是触发事件次数更少,性能更高;可以解决某些乱序问题,如