写一个epoll例子
时间: 2023-08-25 18:11:33 浏览: 112
epoll 例子
5星 · 资源好评率100%
好的,这里是一个简单的 epoll 例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#define MAX_EVENTS 10
int main(int argc, char *argv[]) {
int listen_sock, conn_sock, epoll_fd, nfds, i, n;
struct sockaddr_in serv_addr, cli_addr;
socklen_t cli_len = sizeof(cli_addr);
struct epoll_event ev, events[MAX_EVENTS];
char buffer[1024];
if ((listen_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
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_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(listen_sock, SOMAXCONN) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((epoll_fd = epoll_create1(0)) < 0) {
perror("epoll_create1");
exit(EXIT_FAILURE);
}
ev.events = EPOLLIN;
ev.data.fd = listen_sock;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_sock, &ev) < 0) {
perror("epoll_ctl: listen_sock");
exit(EXIT_FAILURE);
}
while (1) {
nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if (nfds < 0) {
perror("epoll_wait");
exit(EXIT_FAILURE);
}
for (i = 0; i < nfds; ++i) {
if (events[i].data.fd == listen_sock) {
conn_sock = accept(listen_sock, (struct sockaddr *) &cli_addr, &cli_len);
if (conn_sock < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
ev.events = EPOLLIN;
ev.data.fd = conn_sock;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, conn_sock, &ev) < 0) {
perror("epoll_ctl: conn_sock");
exit(EXIT_FAILURE);
}
} else {
n = read(events[i].data.fd, buffer, sizeof(buffer));
if (n < 0) {
perror("read");
exit(EXIT_FAILURE);
}
if (n == 0) {
if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL) < 0) {
perror("epoll_ctl: conn_sock");
exit(EXIT_FAILURE);
}
close(events[i].data.fd);
} else {
if (write(events[i].data.fd, buffer, n) < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
}
}
}
return 0;
}
```
这个程序监听端口 8080,并使用 epoll 实现了一个简单的回显服务器。它可以同时处理多个连接,当有新连接到来时,将其加入 epoll 监听队列中,当某个连接的数据可读时,就读取并回显给客户端。
阅读全文