Implement graceful shutdown
This commit is contained in:
parent
34e77a7c39
commit
04513fb2b6
2 changed files with 48 additions and 7 deletions
|
@ -1,5 +1,33 @@
|
|||
#include <stdio.h>
|
||||
#include "sockets.c"
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
|
||||
int sd;
|
||||
|
||||
int run_server(const char **port_str) {
|
||||
if (open_socket("127.0.0.1", *port_str, &sd) != 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (accept_loop(sd) != 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void sigint_handler(int) {
|
||||
fprintf(stderr, "Gracefully shutting down...\n");
|
||||
|
||||
if (shutdown(sd, 2) != 0) {
|
||||
perror("warning: global shutdown connection failed");
|
||||
}
|
||||
|
||||
if (close(sd) != 0) {
|
||||
perror("warning: global close connection failed");
|
||||
}
|
||||
}
|
||||
|
||||
int main (int argc, char **argv) {
|
||||
if (argc < 2) {
|
||||
|
@ -8,14 +36,21 @@ int main (int argc, char **argv) {
|
|||
}
|
||||
char *port_str = argv[1];
|
||||
|
||||
int sd;
|
||||
if (open_socket("127.0.0.1", port_str, &sd) != 0) {
|
||||
pthread_t thread_id;
|
||||
pthread_create(
|
||||
&thread_id,
|
||||
NULL,
|
||||
(void *) &run_server,
|
||||
&port_str
|
||||
);
|
||||
|
||||
signal(SIGINT, &sigint_handler);
|
||||
|
||||
int res, status;
|
||||
if ((status = pthread_join(thread_id, (void *) &res)) != 0) {
|
||||
fprintf(stderr, "join worker thread: %s\n", strerror(status));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (accept_loop(sd) != 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return res;
|
||||
}
|
|
@ -8,6 +8,8 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
|
||||
int open_socket(const char *ip, const char *port, int *res_sd) {
|
||||
// get address info
|
||||
|
@ -68,6 +70,10 @@ int accept_loop(int sd) {
|
|||
while (1) {
|
||||
int new_sd = accept(sd, NULL, NULL);
|
||||
if (new_sd == -1) {
|
||||
if (errno == EINVAL) {
|
||||
// This is us shutting down and closing the socket (I hope)
|
||||
return 0;
|
||||
}
|
||||
perror("failed to accept new connection");
|
||||
return 1;
|
||||
}
|
||||
|
|
Reference in a new issue