/Epoll.h/
#ifndef _EPOLL_H_INCLUDE_
#define _EPOLL_H_INCLUDE_
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <strings.h>
#include <vector>
#include <errno.h>
#include "MyException.h"
class Epoll
{
public:
Epoll(int flags=EPOLL_CLOEXEC,int noFile=1024);
~Epoll();
void addfd(int fd,uint32_t events=EPOLLIN,bool ETorNot=false);
void modfd(int fd,uint32_t events=EPOLLINT,bool ETorNot=false);
void delfd(int fd);
int wait(int timeout=-1);
int getEventOccurfd(int eventIndex)const;
uint32_t getEvents(int eventIndex)const;
public:
bool isValid()
{
if(m_epollfd==-1)
return false;
return true;
}
void close()
{
if(isValid())
{
::close(m_epollfd);
m_epollfd=-1;
}
}
private:
std::vector<struct epoll_event> events;
int m_epollfd;
int fdNumber;
int nReady;
private:
struct epoll_event event;
};
#endif
#include "Epoll.h"
Epoll::Epoll(int flags,int noFile):fdNumber(0),nReady(0)
{
struct rlimit rlim;
rlim.rlim_cur=rlim.rlim_max=noFile;
if(::setrlimit(RLIMIT_NOFILE,&rlim)==-1)
MY_THROW(ExceptionDerived,"setrlimit error");
m_epollfd=::epoll_create(flags);
if(m_epollfd==-1)
MY_THROW(ExceptionDerived,"epoll_create error");
}
Epoll::~Epoll()
{
this->close();
}
void Epoll::addfd(int fd,uint32_t events,bool ETorNot)
{
bzero(&event,sizeof(event));
event_events=events;
if(ETorNot)
event.events|=EPOLLET;
if(::epoll_ctl(m_epollfd,EPOLL_CTL_ADD,fd,&event)==-1)
MY_THROW(ExceptionDerived,"epoll_ctl_add error");
++fdNumber;
}
void Epoll::modfd(int fd,uint32_t events,bool ETorNot)
{
bzero(&events,sizeof(event));
event.events=events;
if(ETorNot)
event.events|=EPOLLET;
event.data.fd=fd;
if(::epoll_ctl(m_epollfd,EPOLL_CTL_MOD,fd,&event)==-1)
MY_THROW(ExceptionDerived,"epoll_ctl_mod error");
}
void Epoll:delfd(int fd)
{
bzero(&event,sizeof(event));
event.data.fd=fd;
if(::epoll_ctl(m_epollfd,EPOLL_CTL_DEL,fd,&event)==-1)
MY_THROW(ExceptionDerived,"epoll_ctl_del error");
--fdNumber;
}
int Epoll:wait(int timeout)
{
events.resize(fdNumber);
while(true)
{ nReady=epoll_wait(m_epollfd,&*evnets.begin(),fdNumber,timeout);
if(nReady==0)
MY_THROW(ExceptionDerived,"epoll_wait timeout");
else if(nReady==-1)
{
if(errno==EINTR)
continue;
else
MY_THROW(ExceptionDerived,"epoll_wait error");
}
else
return nReady;
}
return -1;
}
int Epoll::getEventOccurfd(int eventIndex)const
{
if(eventIndex>nReady)
MY_THROW(ExceptionDerived,"parameter(s) error");
return events[eventIndex].data.fd;
}
uint32_t Epoll::getEvents(int eventIndex)const
{
if(eventIndex>nReady)
MY_THROW(ExceptionDerieved,"parameter(s) error");
return events[eventIndex].events;
}