From 28dc1ef45b3f158e3f62c0483b5dbb4e8f792149 Mon Sep 17 00:00:00 2001 From: Jakub Jelen Date: Thu, 27 Apr 2023 17:09:38 +0200 Subject: [PATCH] tests: Use sigterm handler for graceful exit Signed-off-by: Jakub Jelen Reviewed-by: Norbert Pocs --- tests/server/test_server/test_server.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/server/test_server/test_server.c b/tests/server/test_server/test_server.c index da0b1b3f..e7d5f739 100644 --- a/tests/server/test_server/test_server.c +++ b/tests/server/test_server/test_server.c @@ -64,6 +64,15 @@ static void sigchld_handler(int signo) { while (waitpid(-1, NULL, WNOHANG) > 0); } +bool done = false; + +static void sigterm_handler(int signo) +{ + (void) signo; + fprintf(stderr, "Received SIGTERM. Gracefully exiting ...\n"); + done = true; +} + int run_server(struct server_state_st *state) { ssh_session session = NULL; @@ -92,6 +101,15 @@ int run_server(struct server_state_st *state) return SSH_ERROR; } + /* Set up SIGTERM handler. */ + sa.sa_handler = sigterm_handler; + sa.sa_flags = 0; + + if (sigaction(SIGTERM, &sa, NULL) != 0) { + fprintf(stderr, "Failed to register SIGTERM handler\n"); + return SSH_ERROR; + } + /* Redirect all the output and errors to the file to avoid mixing up with * the output from the client */ if (state->log_file != NULL) { @@ -227,7 +245,7 @@ int run_server(struct server_state_st *state) printf("Started libssh test server on port %d\n", state->port); - for (;;) { + while (done == false) { session = ssh_new(); if (session == NULL) { fprintf(stderr, "Out of memory\n"); @@ -245,6 +263,9 @@ int run_server(struct server_state_st *state) /* Remove the SIGCHLD handler inherited from parent. */ sa.sa_handler = SIG_DFL; sigaction(SIGCHLD, &sa, NULL); + /* Remove the SIGTERM handler inherited from parent. */ + sa.sa_handler = SIG_DFL; + sigaction(SIGTERM, &sa, NULL); /* Remove socket binding, which allows us to restart the * parent process, without terminating existing sessions. */ ssh_bind_free(sshbind);