Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/lib/net/net_serve.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
#include <errno.h>
#include <signal.h>

#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
Expand All @@ -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];

Expand All @@ -31,14 +48,15 @@ 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 =
accept(server_socket, (struct sockaddr*)&client_addr,
&client_addrlen);

if (client_conn < 0) {
if (errno == EINTR) continue;
perror("accept() failed");
close(server_socket);
exit(1);
Expand Down
9 changes: 2 additions & 7 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading