From 19a83bdb10a94dfc13815ca1da50a21b535f391e Mon Sep 17 00:00:00 2001 From: fadhil riyanto Date: Thu, 26 Sep 2024 21:20:40 +0700 Subject: add eventloop and sigaction handler when SIGINT arrive Signed-off-by: fadhil riyanto --- main.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/main.c b/main.c index 36b4e95..fa37c69 100644 --- a/main.c +++ b/main.c @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -9,7 +10,9 @@ #include #include #include +#include #include +#include #define dbgchr(x) log_info("%c", x) @@ -35,8 +38,12 @@ struct runtime_opts { struct server_ctx { int tcpfd; + + volatile int *need_exit_ptr; }; +volatile int g_need_exit = 0; + static void review_config(struct runtime_opts *r_opts) { // printf("dest: %u\n", r_opts->destport); @@ -102,12 +109,49 @@ static int create_sock_ret_fd(struct sockaddr_storage *ss_addr) return fd; } +static void signal_cb(int signum) +{ + printf("signal detected, exiting...\n"); + g_need_exit = 1; + +} + +static int server_reg_sigaction(void) +{ + struct sigaction sa; + int ret; + + memset(&sa, 0, sizeof(struct sigaction)); + + sa.sa_handler = signal_cb; + + ret = sigaction(SIGINT, &sa, NULL); + if (ret < 0) { + return -1; + } + +} + +static int enter_eventloop(struct server_ctx *srv_ctx) +{ + while(!*srv_ctx->need_exit_ptr) { + + } + + return 0; +} + static int main_server(struct runtime_opts *r_opts) { int ret = 0; - struct server_ctx *srv_ctx; + struct server_ctx *srv_ctx = (struct server_ctx*)malloc(sizeof(struct server_ctx)); + memset(srv_ctx, 0, sizeof(struct server_ctx)); + struct sockaddr_storage ss_addr; + /* link our ptr */ + srv_ctx->need_exit_ptr = &g_need_exit; + review_config(r_opts); if (setup_addr_storage(&ss_addr, r_opts) == -1) { @@ -118,13 +162,22 @@ static int main_server(struct runtime_opts *r_opts) fprintf(stderr, "socket failed\n"); } + if ((ret = server_reg_sigaction()) == -1) { + fprintf(stderr, "signal handler failed\n"); + } + srv_ctx->tcpfd = ret; printf("server listening on %s:%d\n", r_opts->addr, r_opts->listenport); + + if ((ret = enter_eventloop(srv_ctx) == -1)) { + fprintf(stderr, "error eventloop\n"); + } r_opts_clean(r_opts); close(ret); + free(srv_ctx); return 0; -- cgit v1.2.3