Configure PR_SET_PDEATHSIG on Linux and Job Objects on Windows to prevent orphaned subprocesses on program crash
Some checks are pending
Build / build-mac (push) Waiting to run
Build / build-linux (push) Waiting to run
Build / build-win (push) Waiting to run
CodeQL Advanced / Analyze (c-cpp) (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Waiting to run

This commit is contained in:
Andrea Mazzoleni 2026-08-01 18:26:01 +02:00
parent 9a1987e024
commit 1f9ba62800
4 changed files with 73 additions and 7 deletions

View file

@ -765,6 +765,10 @@ int os_script(char** argv, char** envp, const char* run_as_user)
start = os_tick_sec();
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
pid_t ppid = getpid();
#endif
pid = fork();
if (pid < 0) {
os_syslog(OS_LVL_INFO, "failed to fork script=%s, errno=%s(%d)", resolved_path, strerror(errno), errno);
@ -783,6 +787,15 @@ int os_script(char** argv, char** envp, const char* run_as_user)
*/
setpgid(0, 0);
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
/* Send SIGKILL to child if parent daemon dies unexpectedly */
prctl(PR_SET_PDEATHSIG, SIGKILL);
/* exit if parent died before prctl to avoid becoming orphaned */
if (getppid() != ppid) {
_exit(127);
}
#endif
/* drop privileges first (if configured) */
if (run_as_user && run_as_user[0] != 0) {
errno = 0;
@ -933,6 +946,10 @@ int os_command(const char* command, const char* run_as_user, const char* stdin_t
start = os_tick_sec();
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
pid_t ppid = getpid();
#endif
pid = fork();
if (pid < 0) {
os_syslog(OS_LVL_INFO, "failed to fork command=%s, errno=%s(%d)", command, strerror(errno), errno);
@ -954,6 +971,15 @@ int os_command(const char* command, const char* run_as_user, const char* stdin_t
*/
setpgid(0, 0);
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
/* Send SIGKILL to child if parent daemon dies unexpectedly */
prctl(PR_SET_PDEATHSIG, SIGKILL);
/* exit if parent died before prctl to avoid becoming orphaned */
if (getppid() != ppid) {
_exit(127);
}
#endif
if (pipe_fds[1] != -1)
close(pipe_fds[1]); /* Close unused write end */
@ -1157,6 +1183,10 @@ pid_t os_spawn(char** argv, int* stdout_read_fd, int* stderr_read_fd, const char
}
}
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
pid_t ppid = getpid();
#endif
pid = fork();
if (pid < 0) {
os_syslog(OS_LVL_INFO, "failed to fork path=%s, errno=%s(%d)", resolved_path, strerror(errno), errno);
@ -1177,6 +1207,15 @@ pid_t os_spawn(char** argv, int* stdout_read_fd, int* stderr_read_fd, const char
setpgid(0, 0);
#if defined(__linux__) && defined(PR_SET_PDEATHSIG)
/* Send SIGKILL to child if parent daemon dies unexpectedly */
prctl(PR_SET_PDEATHSIG, SIGKILL);
/* exit if parent died before prctl to avoid becoming orphaned */
if (getppid() != ppid) {
_exit(127);
}
#endif
/* drop privileges first (if configured) */
if (run_as_user && run_as_user[0] != 0) {
errno = 0;