Files
ipoim/event_loop.c
2026-03-24 20:44:22 +03:00

64 lines
1.1 KiB
C

#include "event_loop.h"
#include <stdio.h>
#include <errno.h>
#include <sys/epoll.h>
/*
* Macros
*/
#define MAX_EPOLL_EVENTS (20)
/*
* Data
*/
static int _efd = -1;
static loop_cb_t _cb = NULL;
static struct epoll_event _evs[MAX_EPOLL_EVENTS];
/*
* Public API
*/
bool loop_init(loop_cb_t callback) {
_efd = epoll_create1(0);
if (_efd == -1) {
fprintf(stderr, "[!] epoll_create1 failed: %d\n", errno);
return false;
}
_cb = callback;
return true;
}
void loop_deinit() {
close(_efd);
}
bool loop_ctl(int op, int fd, struct epoll_event *event) {
if (epoll_ctl(_efd, op, fd, event) == -1) {
fprintf(stderr, "[!] epoll_ctl failed: %d\n", errno);
return false;
}
return true;
}
bool loop_wait() {
int result = epoll_wait(
_efd,
_evs,
MAX_EPOLL_EVENTS,
-1
);
if (result < 0) {
fprintf(stderr, "[!] epoll_wait failed: %d\n", errno);
return false;
}
if (!result) {
return true;
}
for (int i = 0; i < result; ++i) {
_cb(_evs[i].data.fd, _evs[i].events);
}
return true;
}