gardesk/gar / fe6b01b

Browse files

kill spawned children on exit: use process groups

Authored by mfwolffe <wolffemf@dukes.jmu.edu>
SHA
fe6b01bfe55eae5d69d942eacb8ff096fd8b9a60
Parents
bb19a9d
Tree
d975960

1 changed file

StatusFile+-
M gar/src/config/lua.rs 11 2
gar/src/config/lua.rsmodified
@@ -1,4 +1,5 @@
11
 use std::collections::HashSet;
2
+use std::os::unix::process::CommandExt;
23
 use std::path::PathBuf;
34
 use std::sync::{Arc, Mutex};
45
 
@@ -95,8 +96,10 @@ impl LuaState {
9596
             // SAFETY: Sending signal 0 just checks if process exists
9697
             let exists = unsafe { libc::kill(pid as i32, 0) == 0 };
9798
             if exists {
98
-                tracing::debug!("Sending SIGTERM to PID {}", pid);
99
-                unsafe { libc::kill(pid as i32, libc::SIGTERM); }
99
+                // Kill the entire process group (negative PID) to get children too
100
+                // This handles cases like "sh -c garterm" where sh spawns garterm
101
+                tracing::debug!("Sending SIGTERM to process group {}", pid);
102
+                unsafe { libc::kill(-(pid as i32), libc::SIGTERM); }
100103
             }
101104
         }
102105
     }
@@ -643,9 +646,12 @@ impl LuaConfig {
643646
         let state = Arc::clone(&self.state);
644647
         let exec_fn = self.lua.create_function(move |_, cmd: String| {
645648
             tracing::debug!("exec: {}", cmd);
649
+            // process_group(0) makes the child its own process group leader
650
+            // so we can kill the entire group (including grandchildren) on exit
646651
             if let Ok(child) = std::process::Command::new("sh")
647652
                 .arg("-c")
648653
                 .arg(&cmd)
654
+                .process_group(0)
649655
                 .spawn()
650656
             {
651657
                 let pid = child.id();
@@ -669,9 +675,12 @@ impl LuaConfig {
669675
                 }
670676
             }
671677
             tracing::info!("exec_once: {}", cmd);
678
+            // process_group(0) makes the child its own process group leader
679
+            // so we can kill the entire group (including grandchildren) on exit
672680
             if let Ok(child) = std::process::Command::new("sh")
673681
                 .arg("-c")
674682
                 .arg(&cmd)
683
+                .process_group(0)
675684
                 .spawn()
676685
             {
677686
                 let pid = child.id();