feat: 初步搭建 EpollLoop 框架

This commit is contained in:
2025-09-28 09:37:43 +00:00
parent 6f75dade24
commit aaab39cfd1
2 changed files with 52 additions and 6 deletions
+40 -4
View File
@@ -4,6 +4,7 @@
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <vector>
namespace ouc_server
{
@@ -20,13 +21,48 @@ namespace ouc_server
close(epoll_fd);
}
bool EpollLoop::add_fd(int fd, uint32_t event_flags, std::function<void()> callback)
void EpollLoop::run(int timeout_ms)
{
std::vector<struct epoll_event> events(1024);
int nfds = epoll_wait(epoll_fd, events.data(), events.size(), timeout_ms);
for (int i = 0; i < nfds; ++i)
{
int fd = events[i].data.fd;
if (events_map.count(fd))
events_map[fd].callback();
}
}
bool EpollLoop::add_fd(int fd, uint32_t event_flags, EpollCallback callback)
{
auto ev = pack_event(fd, event_flags);
int code = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
events_map[fd] = Event{fd, event_flags, callback};
return code == 0;
}
bool EpollLoop::modify_fd(int fd, uint32_t event_flags)
{
auto ev = pack_event(fd, event_flags);
int code = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev);
events_map[fd].events = event_flags;
return code == 0;
}
bool EpollLoop::remove_fd(int fd)
{
int code = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, nullptr);
events_map.erase(fd);
return code == 0;
}
struct epoll_event EpollLoop::pack_event(int fd, uint32_t flags)
{
struct epoll_event ev;
ev.events = event_flags;
ev.events = flags;
ev.data.fd = fd;
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
events_map[fd] = Event{fd, event_flags, callback};
return ev;
}
}
}
+12 -2
View File
@@ -14,15 +14,18 @@ namespace ouc_server
{
namespace epoll
{
using EpollCallback = std::function<void()>;
struct Event
{
int fd;
uint32_t events;
std::function<void()> callback;
EpollCallback callback;
};
class EpollLoop
{
public:
private:
int epoll_fd;
std::unordered_map<int, Event> events_map;
@@ -33,7 +36,14 @@ namespace ouc_server
~EpollLoop();
public:
bool add_fd(int, uint32_t, std::function<void()>);
void run(int = -1);
bool add_fd(int, uint32_t, EpollCallback);
bool modify_fd(int, uint32_t);
bool remove_fd(int);
private:
struct epoll_event pack_event(int, uint32_t);
};
}
}