Add explanatory comments above each major block in main.c

This commit is contained in:
Camden Dixie O'Brien 2022-10-13 12:52:10 +01:00
parent 88642c0c3f
commit 2ab4966773

22
main.c
View File

@ -37,6 +37,13 @@ int main(int argc, char *argv[])
(void)argc; (void)argc;
(void)argv; (void)argv;
/*
* Register signal handler for SIGTERM and SIGINT.
*
* The behaviour of signal() is not entirely consistent across
* different implementations, so this should ideally be rewritten
* to use signaction() instead at some point.
*/
if (signal(SIGTERM, handle_exit_signal) == SIG_ERR) { if (signal(SIGTERM, handle_exit_signal) == SIG_ERR) {
fprintf(stderr, "Failed to register SIGTERM signal handler\n"); fprintf(stderr, "Failed to register SIGTERM signal handler\n");
return 1; return 1;
@ -46,12 +53,18 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
/*
* Initialise socket.
*
* Currently only supporting IPv6, and hard-coding address and
* port. Should eventully get address and port from arguments, and
* support IPv4 as well.
*/
int sfd = socket(AF_INET6, SOCK_STREAM, 0); int sfd = socket(AF_INET6, SOCK_STREAM, 0);
if (sfd == -1) { if (sfd == -1) {
fprintf(stderr, "Failed to open socket\n"); fprintf(stderr, "Failed to open socket\n");
return 1; return 1;
} }
const struct sockaddr_in6 haddr = { const struct sockaddr_in6 haddr = {
.sin6_family = AF_INET6, .sin6_family = AF_INET6,
.sin6_port = htons(7070), .sin6_port = htons(7070),
@ -70,6 +83,13 @@ int main(int argc, char *argv[])
socklen_t paddr_size = sizeof(paddr); socklen_t paddr_size = sizeof(paddr);
int cfd; int cfd;
while (!exit_requested) { while (!exit_requested) {
/*
* Accept incoming connection.
*
* If accept() returns with an error and errno is EINTR, this
* should not exit the program as it just indicates that a
* signal arrived while waiting for a connection.
*/
cfd = accept(sfd, (struct sockaddr *)&paddr, &paddr_size); cfd = accept(sfd, (struct sockaddr *)&paddr, &paddr_size);
if (cfd == -1) { if (cfd == -1) {
if (errno == EINTR) if (errno == EINTR)