Initial commit
- basic main.c implementation - event_loop implementation
This commit is contained in:
63
event_loop.c
Normal file
63
event_loop.c
Normal file
@@ -0,0 +1,63 @@
|
||||
#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) {
|
||||
printf("[!] 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) {
|
||||
printf("[!] 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) {
|
||||
printf("[!] 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;
|
||||
}
|
||||
Reference in New Issue
Block a user