Initial commit
- basic main.c implementation - event_loop implementation
This commit is contained in:
99
main.c
Normal file
99
main.c
Normal file
@@ -0,0 +1,99 @@
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/signalfd.h>
|
||||
|
||||
#include "event_loop.h"
|
||||
|
||||
/*
|
||||
* Data
|
||||
*/
|
||||
static bool _to_work = true;
|
||||
static int _sig_fd = -1;
|
||||
|
||||
/*
|
||||
* Private API
|
||||
*/
|
||||
// Initialize signals.
|
||||
// Returns:
|
||||
// - true on success
|
||||
// Remarks:
|
||||
// - loop_init() must be called before this one
|
||||
static bool signals_init() {
|
||||
sigset_t mask;
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGTERM);
|
||||
sigaddset(&mask, SIGINT);
|
||||
sigaddset(&mask, SIGQUIT);
|
||||
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
|
||||
printf("[!] sigprocmask failed: %d\n", errno);
|
||||
return false;
|
||||
}
|
||||
_sig_fd = signalfd(
|
||||
-1,
|
||||
&mask,
|
||||
SFD_NONBLOCK
|
||||
);
|
||||
if (_sig_fd == -1) {
|
||||
printf("[!] signalfd failed: %d\n", errno);
|
||||
return false;
|
||||
}
|
||||
struct epoll_event ev;
|
||||
ev.data.fd = _sig_fd;
|
||||
ev.events = EPOLLIN;
|
||||
bool loop_res = loop_ctl(
|
||||
EPOLL_CTL_ADD,
|
||||
_sig_fd,
|
||||
&ev
|
||||
);
|
||||
if (!loop_res) {
|
||||
close(_sig_fd);
|
||||
printf("[!] loop_ctl failed\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void signals_deinit() {
|
||||
close(_sig_fd);
|
||||
}
|
||||
|
||||
/*
|
||||
* Callbacks and main
|
||||
*/
|
||||
// This callback is called by loop_wait when event happens.
|
||||
static void on_fd_event(int fd, uint32_t events) {
|
||||
// Termination
|
||||
if (fd == _sig_fd) {
|
||||
_to_work = false;
|
||||
}
|
||||
else {
|
||||
printf("[!] Event has happened on an unknown file descriptor\n");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (!loop_init(on_fd_event)) {
|
||||
return 1;
|
||||
}
|
||||
if (!signals_init()) {
|
||||
loop_deinit();
|
||||
return 1;
|
||||
}
|
||||
|
||||
while (_to_work) {
|
||||
if (!loop_wait()) {
|
||||
printf("[!] loop_wait returns false, stopping...\n");
|
||||
break;
|
||||
}
|
||||
printf("--- loop ---\n");
|
||||
}
|
||||
|
||||
signals_deinit();
|
||||
loop_deinit();
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user