From 5c306a453784a33690ae60afa8a462e8561088e1 Mon Sep 17 00:00:00 2001 From: Ruslan Kovtun Date: Sat, 14 Feb 2026 20:40:07 +0200 Subject: [PATCH] Adds graceful shutdown using signal handler --- src/lib/net/net_serve.c | 20 +++++++++++++++++++- src/main.c | 12 ------------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/lib/net/net_serve.c b/src/lib/net/net_serve.c index 8078045..62c8ad9 100644 --- a/src/lib/net/net_serve.c +++ b/src/lib/net/net_serve.c @@ -1,5 +1,16 @@ +#include +#include + #include "header.h" +volatile sig_atomic_t shutdown_requested = false; + +void +signal_hander([[maybe_unused]] int sig) +{ + shutdown_requested = true; +} + /** * Starts a server that listens for incoming connections on the specified host * and port. The server will accept incoming connections and pass them to the @@ -18,6 +29,12 @@ int net_serve(char* host, ProtocolHandler handle_protocol, RequestContext* context) { + struct sigaction sa = {.sa_handler = signal_hander}; + // Termination signal + sigaction(SIGTERM, &sa, nullptr); + // Interrupt from keyboard + sigaction(SIGINT, &sa, nullptr); + int port; char head[50], tail[50]; @@ -30,7 +47,7 @@ net_serve(char* host, ProtocolHandler handle_protocol, RequestContext* context) int server_socket = net_listener(head, port); printf("Serving requests on %d\n", port); - while (1) { + while (!shutdown_requested) { struct sockaddr_in client_addr; socklen_t client_addrlen = sizeof(client_addr); int client_conn = @@ -38,6 +55,7 @@ net_serve(char* host, ProtocolHandler handle_protocol, RequestContext* context) &client_addrlen); if (client_conn < 0) { + if (errno == EINTR) continue; perror("accept() failed"); close(server_socket); exit(1); diff --git a/src/main.c b/src/main.c index 3814e6e..e79937f 100644 --- a/src/main.c +++ b/src/main.c @@ -29,21 +29,9 @@ main() router_add(router, "^/404$", Error404); router_add(router, "^/static/(.*)$", Static); - /* - * Used to check for memory leaks in allocation and deallocation of - * memory - */ - // router_free(router); - // printf("Freed test router\n"); - printf("Server listening on %d\n", PORT); http.ListenAndServe(hostname, router); - /* - * TODO: This is never reached due to infinite listener that stops on - * CTRL + C - * - Need to add a way to handle graceful shut down - */ printf("\n\n\t << Graceful Shutdown >>\n\n"); router_free(router);