diff --git a/gsock.cpp b/gsock.cpp index 4b5da89..9d6ee08 100644 --- a/gsock.cpp +++ b/gsock.cpp @@ -1077,38 +1077,50 @@ bool selector::is_error(const vsock& v) #ifdef WIN32 // Windows: IOCP. Coming soon... #else // Linux: epoll -epoll::epoll() +#include + +epoll::epoll(int MaxListen) : _evec(MaxListen) { - _fd=epoll_create(1024); // this parameter is useless. + _fd = epoll_create(MaxListen); // this parameter is useless. } epoll::~epoll() { close(_fd); } -int epoll::add(const vsock& v,int event) +int epoll::add(vsock& v, int event) { struct epoll_event ev; - ev.events=event; - ev.data.fd=v._vp->sfd; - return epoll_ctl(_fd,EPOLL_CTL_ADD,v._vp->sfd,&ev); + ev.events = event; + ev.data.ptr = &v; + return epoll_ctl(_fd, EPOLL_CTL_ADD, v._vp->sfd, &ev); } -int epoll::mod(const vsock& v,int event) +int epoll::mod(vsock& v, int event) { struct epoll_event ev; - ev.events=event; - ev.data.fd=v._vp->sfd; - return epoll_ctl(_fd,EPOLL_CTL_MOD,v._vp->sfd,&ev); + ev.events = event; + ev.data.ptr = &v; + return epoll_ctl(_fd, EPOLL_CTL_MOD, v._vp->sfd, &ev); } -int epoll::del(const vsock& v,int event) +int epoll::del(vsock& v, int event) { struct epoll_event ev; - ev.events=event; - ev.data.fd=v._vp->sfd; - return epoll_ctl(_fd,EPOLL_CTL_DEL,v._vp->sfd,&ev); + ev.events = event; + ev.data.ptr = &v; + return epoll_ctl(_fd, EPOLL_CTL_DEL, v._vp->sfd, &ev); } -int epoll::wait(epoll_event* events,int maxsize,int timeout) +int epoll::wait(int timeout) { - return epoll_wait(_fd,events,maxsize,timeout); + return _n = epoll_wait(_fd, _evec.data(), _evec.size(), timeout); +} +void epoll::handle(const std::function& callback) +{ + if (_n > 0) + { + for (int i = 0; i < _n; i++) + { + callback(*((vsock*)(_evec[i].data.ptr)), (int)(_evec[i].events)); + } + } } #endif diff --git a/gsock.h b/gsock.h index 24bec5f..f94c8e0 100644 --- a/gsock.h +++ b/gsock.h @@ -229,24 +229,30 @@ private: #else // Linux: epoll #include +#include + class epoll { public: - epoll(); + epoll(int MaxListen); // EPOLLIN, EPOLLOUT, ... - int add(const vsock& v,int event); - int mod(const vsock& v,int event); - int del(const vsock& v,int event); + int add(vsock& v,int event); + int mod(vsock& v,int event); + int del(vsock& v,int event); - // >0: event counts. - // =0: Time up. + // >0: Event counts. + // =0: Timeout. // <0: Error. // Set timeout to -1 for infinity waiting. - // Get data from events[i].events and events[i].data.fd - int wait(struct epoll_event* events,int maxsize,int timeout); + // Call handle() to handle events + int wait(int timeout); + + void handle(const std::function& callback); ~epoll(); private: + std::vector _evec; + int _n; int _fd; }; #endif // End of Platform specific