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