/** * the interface of event. */ class IEvent { public: virtual int addEvent(const Event &event) = 0; virtual int delEvent(const Event &event) = 0; virtual int dispatcher() = 0; virtual ~IEvent() { } };
IEvent的实现类EpollEvent,其中封装了epoll相关的函数。EpollEvent有3个成员,分别是pollCreateSize、epollFd、events,pollCreateSize表示调用epoll_create时传递的参数值,epollFd表示epoll_create的返回值,events是记录事件的map,events中记录了监听事件的信息,当事件来临时被用到。
class EpollEvent : public IEvent { public: EpollEvent() : EpollEvent(16) { } EpollEvent(int createSize) { if (createSize < 16) { createSize = 16; } epollCreateSize = createSize; initEvent(); } virtual int addEvent(const Event &event); virtual int delEvent(const Event &event); virtual int dispatcher(); private: int initEvent() { int epollFd = epoll_create(this->epollCreateSize); if (epollFd <= 0) { perror("create_create error:"); return epollFd; /* here epollFd is -1 */ } this->epollFd = epollFd;return 0; } int epollCreateSize; int epollFd; //Event event; map<int, Event> events; };
-------------------------------------------------------------------------
int EpollEvent::addEvent(const Event &event) { struct epoll_event epollEvent; epollEvent.data.fd = event.fd; epollEvent.events = event.event; int retCode = epoll_ctl(this->epollFd, EPOLL_CTL_ADD, event.fd, &epollEvent); if (retCode < 0) { perror("epoll_ctl error:"); return retCode; } /* add event to this->events */ this->events[event.fd] = event;return 0; } int EpollEvent::delEvent(const Event &event) { struct epoll_event epollEvent; epollEvent.data.fd = event.fd; epollEvent.events = event.event; int retCode = epoll_ctl(this->epollFd, EPOLL_CTL_DEL, event.fd, &epollEvent); if (retCode < 0) { perror("epoll_ctl error:"); return retCode; } this->events.erase(event.fd); return 0; } int EpollEvent::dispatcher() { struct epoll_event epollEvents[32]; //cout << "epoll_wait before" << endl; int nEvents = epoll_wait(epollFd, epollEvents, 32, -1); if (nEvents <= 0) { perror("epoll_wait error:"); return -1; } //cout << "epoll_wait after nEvent" << endl; for (int i = 0; i < nEvents; i++) { int fd = epollEvents[i].data.fd; Event event = this->events[fd]; if (event.callback) { event.callback(fd, event.arg); } } return 0; }