epoll代码框架

2021年09月15日 阅读数:2
这篇文章主要向大家介绍epoll代码框架,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

epoll代码实现框架:markdown

#define MAX_EVENTS 10

struct epoll_event ev, events[MAX_EVENTS];

int listen_sock, conn_sock, nfds, epollfd;

/* Code to set up listening socket, 'listen_sock',
  (socket(), bind(), listen()) omitted */

epollfd = epoll_create1(0);
if (epollfd == -1) {
   perror("epoll_create1");
   exit(EXIT_FAILURE);
}

ev.events  = EPOLLIN;
ev.data.fd = listen_sock;

if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) {
   perror("epoll_ctl: listen_sock");
   exit(EXIT_FAILURE);
}

for (;;) {
   nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
   if (nfds == -1) {
	   perror("epoll_wait");
	   exit(EXIT_FAILURE);
   }

   for (n = 0; n < nfds; ++n) {
	   if (events[n].data.fd == listen_sock) {
		   conn_sock = accept(listen_sock,
							  (struct sockaddr *) &addr, &addrlen);
		   if (conn_sock == -1) {
			   perror("accept");
			   exit(EXIT_FAILURE);
		   }
		   setnonblocking(conn_sock);
		   ev.events = EPOLLIN | EPOLLET;
		   ev.data.fd = conn_sock;
		   if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock,
					   &ev) == -1) {
			   perror("epoll_ctl: conn_sock");
			   exit(EXIT_FAILURE);
		   }
	   } else {
		   do_use_fd(events[n].data.fd);
	   }
   }
}