diff options
author | dec05eba <dec05eba@protonmail.com> | 2020-07-22 18:48:30 +0200 |
---|---|---|
committer | dec05eba <dec05eba@protonmail.com> | 2020-07-22 18:48:30 +0200 |
commit | e9e41c02d4309cd50b5584a8dfc0d7e01cb27e10 (patch) | |
tree | 365b00dba760153e8d88fa143fb7e15a2a1a6448 /src/command.c | |
parent | 93db3b8726f6d7574b71926285e86135e822f9d3 (diff) |
Kill child process when parent dies
Diffstat (limited to 'src/command.c')
-rw-r--r-- | src/command.c | 19 |
1 files changed, 17 insertions, 2 deletions
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 <unistd.h> #include <sys/wait.h> +#include <sys/prctl.h> +#include <signal.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <assert.h> +#include <stdlib.h> #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); |