From 5fe9ba36a28ec92a160bac4bc91138b66b5dfd4f Mon Sep 17 00:00:00 2001 From: MadMaurice Date: Tue, 12 Jan 2021 19:51:05 +0100 Subject: [PATCH] Add signal handler for SIGTERM When the head process receives a SIGTERM we have to forward that to the init process, which in turn has to forward it to the executed process which is jailed. That process can then decide to exit, which also terminates the init and head process through SIGCHILD/wait means. --- main.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/main.c b/main.c index 12097e8..9563625 100644 --- a/main.c +++ b/main.c @@ -8,6 +8,9 @@ #include #include #include +#include + +pid_t pid_child; void drop_root(void) { // Drop root privileges @@ -26,6 +29,15 @@ void drop_root(void) { } } +void forward_signal(int sig) +{ + if(kill(pid_child, sig) == -1) { + printf("Unable to forward signal %d to child\n", sig); + if(sig == SIGTERM) + exit(1); + } +} + char** argdup(int argc, const char** argv) { char** newargs = malloc(sizeof(char*) * (argc+1)); @@ -67,6 +79,12 @@ int main(int argc, const char** argv) if (pid != 0) { + + // Setup signal handler to forward SIGTERM + pid_child = pid; + if(signal(SIGTERM, forward_signal) == SIG_ERR) { + printf("Unable to setup signal handler in head\n"); + } // parent waits for child then exits int status; if(waitpid(pid, &status, 0) == -1) @@ -93,6 +111,14 @@ int main(int argc, const char** argv) pid_t exited_child; int child_status; int err; + + // Setup forward for SIGTERM + pid_child = first_child; + if(signal(SIGTERM, forward_signal) == SIG_ERR) { + printf("Unable to setup signal forward in init. Aborting.\n"); + return 1; + } + do { exited_child = wait(&child_status); err = errno;