From ef276e1e86e4a554141b511757dded2b1f1108fb Mon Sep 17 00:00:00 2001 From: Oskar Date: Mon, 3 Jun 2024 17:59:53 +0200 Subject: make client close sockfd when exiting --- listen.c | 15 +++++++++++++-- test/Makefile | 4 ++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/listen.c b/listen.c index 49bb1aa..b314f2a 100644 --- a/listen.c +++ b/listen.c @@ -10,11 +10,20 @@ #include #include #include +#include // int listen(int sockfd, int backlog); #define __FAIL EXIT_FAILURE #define BACKLOG 128 +int sockfd = -1; +void INThandler () { + + close(sockfd); + fprintf(stderr, " SIGINT\n"); + exit(0); +} + size_t recv_message_loop (int newfd) { size_t rlen = 1024; @@ -43,7 +52,7 @@ size_t recv_message_loop (int newfd) { int main (void) { - int sockfd = -1; // socket fd + // sockfd is at the top of the file!!! int gai_result; // result from getaddrinfo int bind_result = -1; // result from bind struct addrinfo *res; // Pointer to linked list sent back by gai @@ -83,6 +92,8 @@ int main (void) { listen(sockfd, BACKLOG); // Actually listen for connections with the sockfd + signal(SIGINT, INThandler); + while (1) { fprintf(stdout, "Waiting for a connection...\n"); int newfd; @@ -92,7 +103,6 @@ int main (void) { newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size); // Actually accept. Pass the sockfd, cast their_addr to sockaddr and send the address to the function. Pass the addr_size address so we can handle the length. fprintf(stdout, "Connection is being established...\n"); if (newfd == -1) { - fprintf(stderr, "newfd: %d\n", newfd); exit(__FAIL); } @@ -108,6 +118,7 @@ int main (void) { char *msg = "Connected\n"; send(newfd, msg, 10, 0); recv_message_loop(newfd); + close(newfd); } return 0; diff --git a/test/Makefile b/test/Makefile index 6af8165..48a5814 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,6 +1,6 @@ all: release clean: cd .. && make clean - + release: - cd .. && make tests && make beej + cd .. && make tests -- cgit v1.2.3