diff --git a/src/lib/net/net_serve.c b/src/lib/net/net_serve.c index 51cf00a..a1ee641 100644 --- a/src/lib/net/net_serve.c +++ b/src/lib/net/net_serve.c @@ -1,6 +1,17 @@ +#include +#include + #include "header.h" #include "utils/logging/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 @@ -19,6 +30,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]; @@ -31,7 +48,7 @@ net_serve(char* host, ProtocolHandler handle_protocol, RequestContext* context) int server_socket = net_listener(head, port); info("Serving requests on %s\n", host); - while (1) { + while (!shutdown_requested) { struct sockaddr_in client_addr; socklen_t client_addrlen = sizeof(client_addr); int client_conn = @@ -39,6 +56,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 e2ace9e..5aecbe4 100644 --- a/src/main.c +++ b/src/main.c @@ -32,13 +32,8 @@ main() 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 - */ - // info("\n\n\t << Graceful Shutdown >>\n\n"); - // router_free(router); + printf("\n\n\t << Graceful Shutdown >>\n\n"); + router_free(router); return 0; }