Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Forward SIGINT to child process groups for proper hook termination (#136)

Maximilian Roos2ee43b019765
diff --git a/Cargo.lock b/Cargo.lock
index 8c2308272..f5b174aa7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2965,6 +2965,7 @@ dependencies = [
"insta-cmd",
"log",
"minijinja",
+ "nix 0.29.0",
"normalize-path",
"osc8",
"portable-pty",
@@ -2975,6 +2976,7 @@ dependencies = [
"serde_json",
"shell-escape",
"shellexpand",
+ "signal-hook",
"skim",
"strum",
"synoptic",
diff --git a/Cargo.toml b/Cargo.toml
index 811c408a3..e3bd5a13b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -83,6 +83,8 @@ which = "7.0"
[target.'cfg(unix)'.dependencies]
skim = "0.20"
+nix = { version = "0.29", default-features = false, features = ["process", "signal"] }
+signal-hook = { version = "0.3.17", default-features = false, features = ["iterator"] }
[build-dependencies]
vergen-gitcl = { version = "1.0.8", features = ["build"] }
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index ca2dafc85..a545fbbf1 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -679,7 +679,13 @@ pub(crate) fn execute_streaming(
redirect_stdout_to_stderr: bool,
stdin_content: Option<&str>,
) -> anyhow::Result<()> {
+ #[cfg(unix)]
+ use nix::sys::signal::{Signal, kill};
+ #[cfg(unix)]
+ use nix::unistd::Pid;
use std::io::Write;
+ #[cfg(unix)]
+ use std::os::unix::process::CommandExt;
use worktrunk::git::WorktrunkError;
use worktrunk::shell_exec::ShellConfig;
@@ -703,6 +709,12 @@ pub(crate) fn execute_streaming(
};
let mut cmd = shell.command(command);
+
+ // Put child in its own process group so we can forward SIGINT to the entire group.
+ // Uses posix_spawnattr_setpgroup when available; otherwise falls back to fork/exec.
+ #[cfg(unix)]
+ cmd.process_group(0);
+
let mut child = cmd
.current_dir(working_dir)
.stdin(stdin_mode)
@@ -718,6 +730,31 @@ pub(crate) fn execute_streaming(
})
})?;
+ // Child PID equals its PGID since it's the process group leader
+ #[cfg(unix)]
+ let child_pid = Pid::from_raw(child.id() as i32);
+
+ #[cfg(unix)]
+ let (signal_handle, signal_thread) = {
+ use signal_hook::consts::SIGINT;
+ use signal_hook::iterator::Signals;
+
+ let mut signals = Signals::new([SIGINT])
+ .map_err(|e| anyhow::anyhow!("Failed to install SIGINT handler: {e}"))?;
+ let handle = signals.handle();
+
+ let thread = std::thread::spawn(move || {
+ for sig in signals.forever() {
+ if sig == SIGINT {
+ // Forward Ctrl-C to the entire child process group.
+ let _ = kill(Pid::from_raw(-child_pid.as_raw()), Signal::SIGINT);
+ }
+ }
+ });
+
+ (handle, thread)
+ };
+
// Write stdin content if provided (used for hook context JSON)
// We ignore write errors here because:
// 1. The child may have already exited (broken pipe)
@@ -738,6 +775,13 @@ pub(crate) fn execute_streaming(
})
})?;
+ #[cfg(unix)]
+ {
+ // Stop listening for SIGINT and join the forwarding thread.
+ signal_handle.close();
+ let _ = signal_thread.join();
+ }
+
// Check if child was killed by a signal (Unix only)
// This handles Ctrl-C: when SIGINT is sent, the child receives it and terminates,
// and we propagate the signal exit code (128 + signal number, e.g., 130 for SIGINT)
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index c229cc4a7..74fbb35a2 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -402,6 +402,60 @@ check = "echo 'USER_PRE_MERGE' > user_premerge_marker.txt"
);
}
+#[test]
+#[cfg(unix)]
+fn test_pre_merge_hook_receives_sigint() {
+ use nix::sys::signal::{Signal, kill};
+ use nix::unistd::Pid;
+ use std::io::Read;
+
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Project pre-merge hook: write start, then sleep, then write done (if not interrupted)
+ repo.write_project_config(
+ r#"[pre-merge]
+long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
+"#,
+ );
+ repo.commit("Add pre-merge hook");
+
+ // Spawn wt hook pre-merge (skip approval with --force)
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.args(["hook", "pre-merge", "--force"]);
+ let mut child = cmd.spawn().expect("failed to spawn wt hook pre-merge");
+
+ // Wait until hook writes "start" to hook.log (verifies the hook is running)
+ let hook_log = repo.root_path().join("hook.log");
+ wait_for_file(&hook_log, Duration::from_secs(5));
+
+ // Send SIGINT to wt (simulates Ctrl-C)
+ kill(Pid::from_raw(child.id() as i32), Signal::SIGINT).expect("failed to send SIGINT");
+
+ let status = child.wait().expect("failed to wait for wt");
+
+ // Expect conventional Ctrl-C exit code 130
+ assert_eq!(
+ status.code(),
+ Some(130),
+ "wt should exit with 130 on SIGINT, status: {status:?}"
+ );
+
+ // Give the (killed) hook a moment; it must not append "done"
+ thread::sleep(Duration::from_millis(500));
+
+ let mut contents = String::new();
+ std::fs::File::open(&hook_log)
+ .unwrap()
+ .read_to_string(&mut contents)
+ .unwrap();
+ assert!(
+ contents.trim() == "start",
+ "hook should not have reached 'done'; got: {contents:?}"
+ );
+}
+
// ============================================================================
// User Post-Merge Hook Tests
// ============================================================================