Support epoll better

This commit is contained in:
Kirigaya Kazuto 2018-08-26 00:19:17 +08:00
parent e4163a6a7e
commit e527e931ff
2 changed files with 42 additions and 24 deletions

View File

@ -1077,38 +1077,50 @@ bool selector::is_error(const vsock& v)
#ifdef WIN32 // Windows: IOCP. Coming soon...
#else // Linux: epoll
epoll::epoll()
#include <functional>
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;
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;
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;
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<void(vsock&, int)>& callback)
{
if (_n > 0)
{
for (int i = 0; i < _n; i++)
{
callback(*((vsock*)(_evec[i].data.ptr)), (int)(_evec[i].events));
}
}
}
#endif

22
gsock.h
View File

@ -229,24 +229,30 @@ private:
#else // Linux: epoll
#include <sys/epoll.h>
#include <functional>
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<void(vsock&,int)>& callback);
~epoll();
private:
std::vector<struct epoll_event> _evec;
int _n;
int _fd;
};
#endif // End of Platform specific