随想录(epoll的使用)

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

    要说linux下面最好用的接口恐怕就是epoll了。不管是网络编程,还是其他pipe编程,使用epoll都很方便。而且,epoll的函数个数少,结构也非常简单。一般只要学好了epoll_create、epoll_ctl、epoll_wait、close这四个函数就可以了。如果大家有这方面的需求,可以找一本linux编程的书来看一看,相信肯定会有收获。


#include <stdio.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <string.h>

#define MAX_EVENTS 10

static int epoll_fd;
static struct epoll_event events[MAX_EVENTS];

int
main(int argc, char* argv[]){

	struct epoll_event ev;
	int comm_pipes[2];

	//
	//init data
	//
	epoll_fd = epoll_create(1024);
	pipe(comm_pipes);

	//
	//add common_pipes
	//
	ev.events = EPOLLIN;
	ev.data.fd = comm_pipes[0];
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, comm_pipes[0], &ev);

	//
	// send data
	//
	write(comm_pipes[1], "hello", strlen("hello"));
	if(-1 != epoll_wait(epoll_fd, events, MAX_EVENTS, -1)){
		char buf[10];
		read(events[0].data.fd, buf, 10);
		printf("%s\n", buf);
	}

	//
	//close epoll and pipe
	//
	epoll_ctl(epoll_fd, EPOLL_CTL_DEL, comm_pipes[0], NULL);
	close(epoll_fd);
	close(comm_pipes[0]);
	close(comm_pipes[1]);

	return 0;
}

    上面的代码只是抛砖引玉。我自己使用的时候,最常用的框架就是epoll+timer或者是epoll+reactor架构。对于epoll+timer,也就是说在epoll之外,添加一个timer thread,这样的架构对于一般的app代码、或者是server代码,已经是绰绰有余了。用户只要设计好自己的状态机和业务逻辑就可以了。如果本身业务比较复杂,那么一般采用epoll+reactor的架构。大家可以看看云风同学编写的skynet代码,可以很好的说明这一点。对于server端的同学来说,epoll+reactor+lua,这已经是我看到的最快速、最简洁、最便捷的开发方式了。

猜你喜欢

转载自blog.csdn.net/feixiaoxing/article/details/81322639