epoll的应用与回调函数——单线程reactor模式实现

reactor模式也是基于epoll组件基础上利用回调函数实现的,之前文章有讲过epoll主要由三个函数来实现,分别是:

epoll_creat();

epoll_wait();

epoll_ctrl();

epoll中的data,其中有一个void型的指针ptr,是为了能方便把参数传入,在epoll_wait的时候就可以返回我们需要的参数,然后通过这些参数进行判断做相应处理。

在reactor中,同样是以这三个函数作为核心,在epoll_wait等到就绪的fd时,会找到之前设定的对应的回调函数进行相应的处理,以及处理完毕后对该fd需要做epoll_ctrl()。

在reactor中利用链表,可以有效提高并发量。

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

#include <sys/poll.h>
#include <sys/epoll.h>
#include <pthread.h>

#define MAXLNE  4096

#define POLL_SIZE	1024

#define BUFFER_LENGTH		1024
#define MAX_EPOLL_EVENT		1024

#define NOSET_CB		0
#define READ_CB		1
#define WRITE_CB		2
#define ACCEPT_CB	3

typedef int NCALLBACK(int fd, int event, void *arg);


struct nitem  
{
	int fd;
	int status;
	int events;
	void *arg;

	NCALLBACK *readcb;   // epollin
	NCALLBACK *writecb;  // epollout
	NCALLBACK *acceptcb; // epollin
	
	unsigned char sbuffer[BUFFER_LENGTH]; //
	int slength;

	unsigned char rbuffer[BUFFER_LENGTH];
	int rlength;
};

struct itemblock
{

	struct itemblock *next;
	struct nitem *items;

};

struct reactor
{
	int epfd;
	struct itemblock *head;

};

int init_reactor(struct reactor *r);

int read_callback(int fd, int event, void *arg);

int write_callback(int fd, int event, vo
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值