From e9e41c02d4309cd50b5584a8dfc0d7e01cb27e10 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Wed, 22 Jul 2020 18:48:30 +0200 Subject: Kill child process when parent dies --- src/command.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'src/command.c') diff --git a/src/command.c b/src/command.c index c413502..d44c773 100644 --- a/src/command.c +++ b/src/command.c @@ -1,10 +1,13 @@ #include "../include/command.h" #include #include +#include +#include #include #include #include #include +#include #define READ_END 0 #define WRITE_END 1 @@ -12,6 +15,7 @@ int tsl_command_exec(char **args, ProgramOutputCallback output_callback, void *userdata) { int fd[2]; pid_t pid; + pid_t parent_pid = getpid(); /* 1 arguments */ if(args[0] == NULL) @@ -25,14 +29,26 @@ int tsl_command_exec(char **args, ProgramOutputCallback output_callback, void *u pid = fork(); if(pid == -1) { perror("Failed to fork"); + close(fd[READ_END]); + close(fd[WRITE_END]); return -3; } else if(pid == 0) { /* child */ + if(prctl(PR_SET_PDEATHSIG, SIGTERM) == -1) { + perror("prctl(PR_SET_PDEATHSIG, SIGTERM) failed"); + exit(127); + } + + /* Test if the parent died before the above call to prctl */ + if(getppid() != parent_pid) + exit(127); + dup2(fd[WRITE_END], STDOUT_FILENO); close(fd[READ_END]); close(fd[WRITE_END]); execvp(args[0], args); - return 0; + perror("execvp"); + exit(127); } else { /* parent */ int result = 0; int status; @@ -71,7 +87,6 @@ int tsl_command_exec(char **args, ProgramOutputCallback output_callback, void *u if(exit_status != 0) { char **arg = args; fprintf(stderr, "Failed to execute program ("); - while(*arg) { if(arg != args) fputc(' ', stderr); -- cgit v1.2.3