epoll函数使用实例
时间: 2023-09-03 20:10:32 浏览: 108
epoll的使用Sample
epoll是Linux下高效的I/O多路复用机制,可以同时监控多个文件描述符的状态,当某个文件描述符发生变化时,epoll会通知应用程序进行处理。
下面是一个简单的epoll使用实例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_EVENTS 10
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int listen_fd, conn_fd, epoll_fd, n;
char buf[BUF_SIZE];
struct sockaddr_in serv_addr, cli_addr;
socklen_t cli_len = sizeof(cli_addr);
struct epoll_event ev, events[MAX_EVENTS];
// 创建监听socket
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd == -1) {
perror("socket error");
exit(EXIT_FAILURE);
}
// 绑定地址和端口
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(8080);
if (bind(listen_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) {
perror("bind error");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(listen_fd, 5) == -1) {
perror("listen error");
exit(EXIT_FAILURE);
}
// 创建epoll
epoll_fd = epoll_create(1);
if (epoll_fd == -1) {
perror("epoll_create error");
exit(EXIT_FAILURE);
}
// 将监听socket加入epoll
ev.events = EPOLLIN;
ev.data.fd = listen_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) == -1) {
perror("epoll_ctl error");
exit(EXIT_FAILURE);
}
while (1) {
// 等待事件
n = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if (n == -1) {
perror("epoll_wait error");
exit(EXIT_FAILURE);
}
// 处理事件
for (int i = 0; i < n; i++) {
if (events[i].data.fd == listen_fd) {
// 有新的连接
conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len);
if (conn_fd == -1) {
perror("accept error");
continue;
}
printf("New connection from %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
// 将连接socket加入epoll
ev.events = EPOLLIN;
ev.data.fd = conn_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, conn_fd, &ev) == -1) {
perror("epoll_ctl error");
exit(EXIT_FAILURE);
}
} else {
// 有数据可读
int fd = events[i].data.fd;
n = read(fd, buf, BUF_SIZE);
if (n == -1) {
perror("read error");
continue;
}
if (n == 0) {
// 对方关闭连接
printf("Connection closed\n");
if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
perror("epoll_ctl error");
exit(EXIT_FAILURE);
}
close(fd);
} else {
// 输出数据
buf[n] = '\0';
printf("Received %d bytes: %s\n", n, buf);
}
}
}
}
// 关闭监听socket
close(listen_fd);
return 0;
}
```
这个程序使用epoll实现了一个简单的回显服务器,当有新的连接时,将连接socket加入epoll,当连接有数据可读时,读取数据并输出。
阅读全文