linux C epoll机制示例代码
时间: 2023-08-19 19:05:59 浏览: 117
以下是一个简单的Linux C epoll机制示例代码,用于监听文件描述符的可读事件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#define MAX_EVENTS 10
int main() {
int fd, sockfd, n, epollfd;
char buffer[256];
struct sockaddr_in serveraddr, clientaddr;
socklen_t clientlen = sizeof(clientaddr);
struct epoll_event ev, events[MAX_EVENTS];
// 创建socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
// 绑定地址
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(5000);
if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("ERROR on binding");
exit(1);
}
// 监听
listen(sockfd, 5);
// 创建epoll实例
epollfd = epoll_create1(0);
if (epollfd == -1) {
perror("epoll_create1");
exit(EXIT_FAILURE);
}
// 添加sockfd到epoll实例中
ev.events = EPOLLIN;
ev.data.fd = sockfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
perror("epoll_ctl: sockfd");
exit(EXIT_FAILURE);
}
// 等待事件发生
while (1) {
n = epoll_wait(epollfd, events, MAX_EVENTS, -1);
for (int i = 0; i < n; i++) {
// 如果是sockfd可读事件,则接收客户端连接
if (events[i].data.fd == sockfd) {
fd = accept(sockfd, (struct sockaddr *) &clientaddr, &clientlen);
if (fd < 0) {
perror("ERROR on accept");
exit(1);
}
printf("Client connected\n");
// 将新的连接fd添加到epoll实例中
ev.events = EPOLLIN;
ev.data.fd = fd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
perror("epoll_ctl: fd");
exit(EXIT_FAILURE);
}
}
// 如果是其他fd可读事件,则接收数据
else {
bzero(buffer, 256);
if (read(events[i].data.fd, buffer, 255) < 0) {
perror("ERROR reading from socket");
exit(1);
}
printf("Message received: %s\n", buffer);
}
}
}
// 关闭socket和epoll实例
close(sockfd);
close(epollfd);
return 0;
}
```
以上代码监听端口5000,接收客户端连接并接收数据。通过epoll机制,可以同时监控多个文件描述符的可读事件,从而提高程序的效率。
阅读全文