浅析epoll – epoll例子以及分析

作者: NickYang 分类: 技术文章,程序开发 发布时间: 2013-01-06 09:15

上篇我们讲到epoll的函数和性能。这一篇用用这些个函数,给出一个最简单的epoll的例子。

//   
// a simple echo server using epoll in linux  
//   
// 2009-11-05  
// by sparkling  
//   
#include <sys/socket.h>  
#include <sys/epoll.h>  
#include <netinet/in.h>  
#include <arpa/inet.h>  
#include <fcntl.h>  
#include <unistd.h>  
#include <stdio.h>  
#include <errno.h>  
#include <iostream>  
using namespace std;  
#define MAX_EVENTS 500  
struct myevent_s  
{  
    int fd;  
    void (*call_back)(int fd, int events, void *arg);  
    int events;  
    void *arg;  
    int status; // 1: in epoll wait list, 0 not in  
    char buff[128]; // recv data buffer  
    int len;  
    long last_active; // last active time  
};  
// set event  
void EventSet(myevent_s *ev, int fd, void (*call_back)(int, int, void*), void *arg)  
{  
    ev->fd = fd;  
    ev->call_back = call_back;  
    ev->events = 0;  
    ev->arg = arg;  
    ev->status = 0;  
    ev->last_active = time(NULL);  
}  
// add/mod an event to epoll  
void EventAdd(int epollFd, int events, myevent_s *ev)  
{  
    struct epoll_event epv = {0, {0}};  
    int op;  
    epv.data.ptr = ev;  
    epv.events = ev->events = events;  
    if(ev->status == 1){  
        op = EPOLL_CTL_MOD;  
    }  
    else{  
        op = EPOLL_CTL_ADD;  
        ev->status = 1;  
    }  
    if(epoll_ctl(epollFd, op, ev->fd, &epv) < 0)  
        printf("Event Add failed[fd=%d]/n", ev->fd);  
    else  
        printf("Event Add OK[fd=%d]/n", ev->fd);  
}  
// delete an event from epoll  
void EventDel(int epollFd, myevent_s *ev)  
{  
    struct epoll_event epv = {0, {0}};  
    if(ev->status != 1) return;  
    epv.data.ptr = ev;  
    ev->status = 0;  
    epoll_ctl(epollFd, EPOLL_CTL_DEL, ev->fd, &epv);  
}  
int g_epollFd;  
myevent_s g_Events[MAX_EVENTS+1]; // g_Events[MAX_EVENTS] is used by listen fd  
void RecvData(int fd, int events, void *arg);  
void SendData(int fd, int events, void *arg);  
// accept new connections from clients  
void AcceptConn(int fd, int events, void *arg)  
{  
    struct sockaddr_in sin;  
    socklen_t len = sizeof(struct sockaddr_in);  
    int nfd, i;  
    // accept  
    if((nfd = accept(fd, (struct sockaddr*)&sin, &len)) == -1)  
    {  
        if(errno != EAGAIN && errno != EINTR)  
        {  
            printf("%s: bad accept", __func__);  
        }  
        return;  
    }  
    do  
    {  
        for(i = 0; i < MAX_EVENTS; i++)  
        {  
            if(g_Events[i].status == 0)  
            {  
                break;  
            }  
        }  
        if(i == MAX_EVENTS)  
        {  
            printf("%s:max connection limit[%d].", __func__, MAX_EVENTS);  
            break;  
        }  
        // set nonblocking  
        if(fcntl(nfd, F_SETFL, O_NONBLOCK) < 0) break;  
        // add a read event for receive data  
        EventSet(&g_Events[i], nfd, RecvData, &g_Events[i]);  
        EventAdd(g_epollFd, EPOLLIN|EPOLLET, &g_Events[i]);  
        printf("new conn[%s:%d][time:%d]/n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), g_Events[i].last_active);  
    }while(0);  
}  
// receive data  
void RecvData(int fd, int events, void *arg)  
{  
    struct myevent_s *ev = (struct myevent_s*)arg;  
    int len;  
    // receive data  
    len = recv(fd, ev->buff, sizeof(ev->buff)-1, 0);    
    EventDel(g_epollFd, ev);  
    if(len > 0)  
    {  
        ev->len = len;  
        ev->buff[len] = '/0';  
        printf("C[%d]:%s/n", fd, ev->buff);  
        // change to send event  
        EventSet(ev, fd, SendData, ev);  
        EventAdd(g_epollFd, EPOLLOUT|EPOLLET, ev);  
    }  
    else if(len == 0)  
    {  
        close(ev->fd);  
        printf("[fd=%d] closed gracefully./n", fd);  
    }  
    else  
    {  
        close(ev->fd);  
        printf("recv[fd=%d] error[%d]:%s/n", fd, errno, strerror(errno));  
    }  
}  
// send data  
void SendData(int fd, int events, void *arg)  
{  
    struct myevent_s *ev = (struct myevent_s*)arg;  
    int len;  
    // send data  
    len = send(fd, ev->buff, ev->len, 0);  
    ev->len = 0;  
    EventDel(g_epollFd, ev);  
    if(len > 0)  
    {  
        // change to receive event  
        EventSet(ev, fd, RecvData, ev);  
        EventAdd(g_epollFd, EPOLLIN|EPOLLET, ev);  
    }  
    else  
    {  
        close(ev->fd);  
        printf("recv[fd=%d] error[%d]/n", fd, errno);  
    }  
}  
void InitListenSocket(int epollFd, short port)  
{  
    int listenFd = socket(AF_INET, SOCK_STREAM, 0);  
    fcntl(listenFd, F_SETFL, O_NONBLOCK); // set non-blocking  
    printf("server listen fd=%d/n", listenFd);  
    EventSet(&g_Events[MAX_EVENTS], listenFd, AcceptConn, &g_Events[MAX_EVENTS]);  
    // add listen socket  
    EventAdd(epollFd, EPOLLIN|EPOLLET, &g_Events[MAX_EVENTS]);  
    // bind & listen  
    sockaddr_in sin;  
    bzero(&sin, sizeof(sin));  
    sin.sin_family = AF_INET;  
    sin.sin_addr.s_addr = INADDR_ANY;  
    sin.sin_port = htons(port);  
    bind(listenFd, (const sockaddr*)&sin, sizeof(sin));  
    listen(listenFd, 5);  
}  
int main(int argc, char **argv)  
{  
    short port = 12345; // default port  
    if(argc == 2){  
        port = atoi(argv[1]);  
    }  
    // create epoll  
    g_epollFd = epoll_create(MAX_EVENTS);  
    if(g_epollFd <= 0) printf("create epoll failed.%d/n", g_epollFd);  
    // create & bind listen socket, and add to epoll, set non-blocking  
    InitListenSocket(g_epollFd, port);  
    // event loop  
    struct epoll_event events[MAX_EVENTS];  
    printf("server running:port[%d]/n", port);  
    int checkPos = 0;  
    while(1){  
        // a simple timeout check here, every time 100, better to use a mini-heap, and add timer event  
        long now = time(NULL);  
        for(int i = 0; i < 100; i++, checkPos++) // doesn't check listen fd  
        {  
            if(checkPos == MAX_EVENTS) checkPos = 0; // recycle  
            if(g_Events[checkPos].status != 1) continue;  
            long duration = now - g_Events[checkPos].last_active;  
            if(duration >= 60) // 60s timeout  
            {  
                close(g_Events[checkPos].fd);  
                printf("[fd=%d] timeout[%d--%d]./n", g_Events[checkPos].fd, g_Events[checkPos].last_active, now);  
                EventDel(g_epollFd, &g_Events[checkPos]);  
            }  
        }  
        // wait for events to happen  
        int fds = epoll_wait(g_epollFd, events, MAX_EVENTS, 1000);  
        if(fds < 0){  
            printf("epoll_wait error, exit/n");  
            break;  
        }  
        for(int i = 0; i < fds; i++){  
            myevent_s *ev = (struct myevent_s*)events[i].data.ptr;  
            if((events[i].events&EPOLLIN)&&(ev->events&EPOLLIN)) // read event  
            {  
                ev->call_back(ev->fd, events[i].events, ev->arg);  
            }  
            if((events[i].events&EPOLLOUT)&&(ev->events&EPOLLOUT)) // write event  
            {  
                ev->call_back(ev->fd, events[i].events, ev->arg);  
            }  
        }  
    }  
    // free resource  
    return 0;  
}

上面是一个echo server的例子,下来我们看下echo client的例子

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define MAXDATASIZE 100 // max number of bytes we can get at once

int main(int argc, char *argv[])
{
	int sockfd, numbytes;
	char buf[MAXDATASIZE];
	struct hostent *he;
	struct sockaddr_in their_addr; // connector'saddress information

	if (( argc == 1) || (argc==2) ) 
	{
		fprintf(stderr,"usage: client hostname\nEx:\n$./client01 ip port\n");
		exit(1);
	}

	if ((he=gethostbyname(argv[1])) == NULL) 
	{ // get the host info
		herror("gethostbyname");
		exit(1);
	}

	if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) 
	{
		perror("socket");
		exit(1);
	}

	their_addr.sin_family = AF_INET; // host byte order
	their_addr.sin_port = htons(atoi(argv[2])); // short, network byte order
	their_addr.sin_addr = *((struct in_addr *)he->h_addr);
	memset(their_addr.sin_zero, '', sizeof their_addr.sin_zero);

	if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof their_addr) == -1) 
	{
		perror("connect");
		exit(1);
	}

	while( 1 )
	{
		if(send(sockfd, "hello, this is client message!", strlen("hello, this is client message!"), 0 ) == -1)
		{
			perror("send");
		}

		if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
		{
			perror("recv");
		}
		else if( numbytes == 0 )
		{
			printf("Remote server has shutdown!\n");
			break;
		}

		buf[numbytes] = '';

		printf("Received: %s \n",buf);
		sleep(1);
	}

	close(sockfd);
	return 0;
}

以上客户端和服务器例子均来自网络,自己没有单独写,因为觉得自己写了跟着个差不多还浪费时间,大家有兴趣可以去研究下libevent和libev,这都是很好用的C风格的epoll网络库,或者之际看ASIO吧。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

  • 神8

    2018 年 9 月 17 日 08:42

    感谢版主的资料.对于学习要虚心,哪来的勇气恶语中伤?就像你饿的要死了,好心人给一个馒头,你破口大骂好心人没给你水?

  • weiwangchao

    2013 年 11 月 1 日 11:02

    排版不咋的啊?复制到别处不像样子。

    1. eliteYang

      2013 年 11 月 1 日 14:51

      这都是什么毛病,伸手党还jjyy的。再说了,在我的网站上排版也没什么问题。如果嫌排版有问题,请不要复制,谢谢!

      1. weiwangchao

        2013 年 11 月 1 日 18:00

        擦,你才jjyy,放到网上有意见提一下有问题吗?怕提意见不要放网上来,自己硬盘里留着。

        1. eliteYang

          2013 年 11 月 1 日 19:08

          你这叫提意见,你这叫找茬。你具体说有什么意见?你说排版,我就想知道,哪里排版有问题,你不会拷贝吧!

          1. dfasf

            2013 年 11 月 3 日 23:07

            没看懂吗?拷贝到别处就格式全乱,说明你这个排版兼容性太差。你随便复制到word或txt看看效果

            1. eliteYang

              2013 年 11 月 4 日 11:18

              你是选中代码然后拷贝的吧,都说了你不会用了。正确的做法是:鼠标放在代码上会出现一个工具条,然后点expand code,按ctrl + c,拷出来绝对没有问题,这些我都是在IDE中排好版的代码,怎么会出现格式乱呢。以后麻烦先琢磨怎么用插件。

              1. Yu

                2015 年 7 月 5 日 13:48

                人家说ctrl+A ,ctrl+C, ctrl+V,不告而转后发现代码乱了~
                哈哈哈哈哈哈哈

发表评论

电子邮件地址不会被公开。 必填项已用*标注