From 1697bab6c12d7f00451a82a12c75181ccb72fb78 Mon Sep 17 00:00:00 2001 From: Bohdan Katsevych <94533356+bkatsevych@users.noreply.github.com> Date: Fri, 29 Mar 2024 15:17:14 +0100 Subject: [PATCH] fix(utils): use revursive find for kill_child_procs() --- src/utils.rs | 38 ++++++-------------------------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index 7d9763e..61fc97b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -18,16 +18,12 @@ pub fn kill_child_procs() { let current_pid = process::id(); println!("Signal caught for {} ", current_pid); - let processes = system.processes(); - for (&pid, proc) in processes { - if proc.parent() == Some(sysinfo::Pid::from_u32(current_pid)) { - println!("Terminating {}", pid); - proc.kill_with(Signal::Term); - println!("Waiting for {} termination", pid); - proc.wait(); - println!("{} exited", pid); - println!("Killing {}", pid); + let child_pids = find_child_processes_recursive(&system, sysinfo::Pid::from_u32(current_pid)); + + for pid in child_pids { + if let Some(proc) = system.process(pid) { + println!("Killing child process {} ", pid); proc.kill(); } } @@ -35,44 +31,22 @@ pub fn kill_child_procs() { process::exit(1); } -// pub fn children(pid: u32, ) -> Vec { -// let system: &System = System::new_all(); -// let mut children: Vec= Vec::new(); -// let processes = system.processes(); - -// for (&_p, proc) in processes { -// if proc.parent() == Some(Pid::from_u32(pid)) { -// children.push(proc); -// } -// } - -// children -// } - -// Function to recursively determine all child processes with `pid` as the root pub fn find_child_processes_recursive(system: &System, pid: Pid) -> Vec { - // let mut system = System::new_all(); let mut child_pids = Vec::new(); - // Recursively find child processes fn find_children(system: &System, pid: Pid, child_pids: &mut Vec) { - // Iterate through all processes for (process_id, process) in system.processes() { - // Check if the process has `pid` as its parent if let Some(parent_pid) = process.parent() { if parent_pid == pid { - // If so, add it to the list of child processes let child_pid = *process_id; child_pids.push(child_pid); - // Recursively find children of the current process find_children(system, child_pid, child_pids); } } } } - // Start the recursive search from the root process find_children(system, pid, &mut child_pids); child_pids -} \ No newline at end of file +}