C++ epoll示例代码
时间: 2023-03-28 21:02:21 浏览: 245
以下是一个简单的 C epoll 示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#define MAX_EVENTS 10
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int server_fd, client_fd, epoll_fd, nfds, n, i;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
struct epoll_event ev, events[MAX_EVENTS];
char buf[BUF_SIZE];
// 创建 socket
server_fd = socket(AF_INET, SOCK_STREAM, );
if (server_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 绑定地址
memset(&server_addr, , sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(808);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 监听
if (listen(server_fd, SOMAXCONN) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
// 创建 epoll
epoll_fd = epoll_create1();
if (epoll_fd == -1) {
perror("epoll_create1");
exit(EXIT_FAILURE);
}
// 添加 server_fd 到 epoll
ev.events = EPOLLIN;
ev.data.fd = server_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &ev) == -1) {
perror("epoll_ctl: server_fd");
exit(EXIT_FAILURE);
}
while (1) {
// 等待事件
nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if (nfds == -1) {
perror("epoll_wait");
exit(EXIT_FAILURE);
}
// 处理事件
for (i = ; i < nfds; i++) {
if (events[i].data.fd == server_fd) {
// 有新连接
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
// 添加 client_fd 到 epoll
ev.events = EPOLLIN;
ev.data.fd = client_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &ev) == -1) {
perror("epoll_ctl: client_fd");
exit(EXIT_FAILURE);
}
} else {
// 有数据可读
n = read(events[i].data.fd, buf, BUF_SIZE);
if (n == -1) {
perror("read");
exit(EXIT_FAILURE);
} else if (n == ) {
// 客户端关闭连接
if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL) == -1) {
perror("epoll_ctl: client_fd");
exit(EXIT_FAILURE);
}
close(events[i].data.fd);
} else {
// 回显数据
if (write(events[i].data.fd, buf, n) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
}
}
}
return ;
}
阅读全文