use std::process::Command;
#[derive(Debug, Clone)]
pub struct ClaudeProcessInfo {
pub pid: i32,
pub comm: String,
}
pub fn is_process_alive(pid: i32) -> bool {
Command::new("ps")
.args(["-p", &pid.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
pub fn get_parent_pid() -> Option<i32> {
let pid = std::process::id() as i32;
get_process_info(pid).map(|info| info.ppid)
}
pub fn find_claude_process() -> Option<ClaudeProcessInfo> {
find_claude_process_from_pid(get_parent_pid()?)
}
fn find_claude_process_from_pid(start_pid: i32) -> Option<ClaudeProcessInfo> {
let mut current_pid = start_pid;
let mut visited = std::collections::HashSet::new();
for _ in 0..50 {
if current_pid <= 1 || visited.contains(¤t_pid) {
break;
}
visited.insert(current_pid);
let Some(info) = get_process_info(current_pid) else {
break;
};
if is_claude_process(&info.comm) {
return Some(ClaudeProcessInfo {
pid: current_pid,
comm: info.comm,
});
}
current_pid = info.ppid;
}
None
}
struct ProcessInfo {
ppid: i32,
comm: String,
}
fn get_process_info(pid: i32) -> Option<ProcessInfo> {
let output = Command::new("ps")
.args(["-o", "ppid=,comm=", "-p", &pid.to_string()])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
let line = stdout.trim();
let mut parts = line.split_whitespace();
let ppid: i32 = parts.next()?.parse().ok()?;
let comm = parts.next()?.to_string();
Some(ProcessInfo { ppid, comm })
}
fn is_claude_process(comm: &str) -> bool {
let comm_lower = comm.to_lowercase();
comm_lower == "node" || comm_lower.contains("claude") || comm_lower.contains("electron")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_process_alive_self() {
assert!(is_process_alive(std::process::id() as i32));
}
#[test]
fn test_is_process_alive_invalid_pid() {
assert!(!is_process_alive(999_999_999));
}
#[test]
fn test_get_parent_pid() -> Result<(), String> {
let ppid = get_parent_pid().ok_or("expected parent pid")?;
assert!(ppid > 0);
Ok(())
}
#[test]
fn test_get_process_info_self() {
let pid = std::process::id() as i32;
let info = get_process_info(pid);
assert!(info.is_some(), "should get info for own process");
}
#[test]
fn test_get_process_info_invalid_pid() {
let info = get_process_info(999_999_999);
assert!(info.is_none());
}
}