epoll简单模型
根据套接字需求不同,使用epoll_ctl进行增加修改删除
接口的基本封装:

class EpollData {
public:
EpollData() { m_data.u64 = 0; }//联合体公用一段内存空间 }
EpollData(void* ptr) { m_data.ptr = ptr; }
explicit EpollData(int fd) { m_data.fd = fd; } //使用explicit关键字防止隐式类型转换
explicit EpollData(uint32_t u32) { m_data.u32 = u32; }
explicit EpollData(uint64_t u64) { m_data.u64 = u64; }
EpollData(const EpollData& data) { m_data.u64 = data.m_data.u64; } //允许复制
public:
EpollData& operator=(const EpollData&data) {
if (this != &data)
m_data.u64 = data.m_data.u64;
return *this;
}
EpollData& operator=(void* data) { //使用void*为参数,函数可以接收任意类型的指针
m_data.ptr = data;
return *this;
}
EpollData& operator=(int data) {
m_data.fd = data;
return *this;
}
EpollData& operator=(uint32_t data) {
m_data.u32 = data;
return *this;
}
EpollData& operator=(uint64_t data) {
m_data.u64 = data;
return *this;
}
operator epoll_data_t() { return m_data; }
operator epoll_data_t()const { return m_data; }
operator epoll_data_t*() { return &m_data; }
operator const epoll_data_t* ()const { return &m_data; }
private:
epoll_data_t m_data;
};
上述代码用于创建EpollData基础类型,epoll_data_t是一个union类型,共享一段内存空间,因此,赋值操作时只需要赋值最大的uint64就可以。
class CEpoll
{
public:
CEpoll() {
m_epoll = -1;
}
~CEpoll() {
Close();
}
public:
CEpoll(const CEpoll&) = delete; //禁用拷贝构造函数
CEpoll& operator=(const CEpoll&) = delete;//禁用等号重载
public:
operator int()const { return m_epoll; }//隐式类型转换成const int
public:
int Create(unsigned count) {
if (m_epoll != -1)return -1;
m_epoll = epoll_create(count);
if (m_epoll == -1)return -2;
return 0;
}
ssize_t WaitEvents(EPEvent &events,int timeout=10) {//返回值小于零表示错误,等于零表示无事发生,大于零表示拿到事件
if (m_epoll == -1)return -1;
EPEvent evs(EVENT_SIZE);
int ret = epoll_wait(m_epoll,evs.data(),(int)evs.size(),timeout); //vector.data返回一个指向数组第一个元素的指针
if (ret == -1) {
if ((errno == EINTR)||(errno==EAGAIN)) { //系统调用被中断或者等待不算错误
return 0;
}
return -2;
}
if (ret > (int)events.size())events.resize(ret);
memcpy(events.data(), evs.data(), sizeof(epoll_event)* ret);
return ret;
}
int Add(int fd,const EpollData& data=EpollData((void*)0),uint32_t events=EPOLLIN) { //EPOLLIN表示可读事件。
if (m_epoll == -1)return -1;
epoll_event ev = { events,data };
int ret = epoll_ctl(m_epoll,EPOLL_CTL_ADD,fd,&ev);
if (ret == -1)return -2;
return 0;
}
int Modify(int fd, uint32_t events ,const EpollData& data = EpollData((void*)0)) {
if (m_epoll == -1)return -1;
epoll_event ev = { events,data };
int ret = epoll_ctl(m_epoll, EPOLL_CTL_MOD, fd, &ev);
if (ret == -1)return -2;
return 0;
}
int Del(int fd) {
if (m_epoll == -1)return -1;
int ret = epoll_ctl(m_epoll, EPOLL_CTL_DEL, fd, NULL);
if (ret == -1)return -2;
return 0;
}
void Close() {
if (m_epoll != -1) {
int fd = m_epoll; //避险编程,将赋值操作放在关闭操作前面
m_epoll = -1;
close(fd);
}
}
private:
int m_epoll;
};
本文介绍了Epoll的基本概念,包括EpollData和CEpoll类的封装,展示了如何使用epoll_ctl进行套接字的增加、修改和删除操作,以及epoll_create、epoll_wait等关键函数的用法。
4189






