fix: use PR_SET_PDEATHSIG so to ensure child processes are killed in a timely manner

This commit is contained in:
Michael Bolin
2025-07-19 11:12:06 -04:00
parent 018003e52f
commit 32767b7ee1
3 changed files with 25 additions and 0 deletions

1
codex-rs/Cargo.lock generated
View File

@@ -669,6 +669,7 @@ dependencies = [
"fs2",
"futures",
"landlock",
"libc",
"maplit",
"mcp-types",
"mime_guess",

View File

@@ -22,6 +22,7 @@ env-flags = "0.1.1"
eventsource-stream = "0.2.3"
fs2 = "0.4.3"
futures = "0.3"
libc = "0.2.174"
mcp-types = { path = "../mcp-types" }
mime_guess = "2.0"
rand = "0.9"

View File

@@ -384,6 +384,29 @@ async fn spawn_child_async(
cmd.env(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR, "1");
}
// If this Codex process dies (including being killed via SIGKILL), we want
// any child processes that were spawned as part of a `"shell"` tool call
// to also be terminated.
#[cfg(target_os = "linux")]
unsafe {
cmd.pre_exec(|| {
// This prctl call effectively requests, "deliver SIGTERM when my
// current parent dies."
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
return Err(io::Error::last_os_error());
}
// Though if there was a race condition and this pre_exec() block is
// run _after_ the parent (i.e., the Codex process) has already
// exited, then the parent is the _init_ process (which will never
// die), so we should just terminate the child process now.
if libc::getppid() == 1 {
libc::raise(libc::SIGTERM);
}
Ok(())
});
}
match stdio_policy {
StdioPolicy::RedirectForShellTool => {
// Do not create a file descriptor for stdin because otherwise some