pub fn process_name(pid: i32) -> Option<String> {
use sysinfo::{Pid, ProcessesToUpdate, System};
if pid <= 0 {
return None;
}
let p = Pid::from(pid as usize);
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::Some(&[p]), true);
sys.process(p)
.map(|pr| pr.name().to_string_lossy().to_string())
.filter(|n| !n.is_empty())
}
pub fn process_cmdline(pid: i32) -> Option<Vec<String>> {
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
if pid <= 0 {
return None;
}
let p = Pid::from(pid as usize);
let mut sys = System::new();
sys.refresh_processes_specifics(
ProcessesToUpdate::Some(&[p]),
true,
ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
);
let cmd: Vec<String> = sys
.process(p)?
.cmd()
.iter()
.map(|s| s.to_string_lossy().to_string())
.collect();
(!cmd.is_empty()).then_some(cmd)
}
#[cfg(target_os = "linux")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}
#[cfg(target_os = "macos")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
use std::ffi::OsString;
use std::os::raw::{c_int, c_void};
use std::os::unix::ffi::OsStringExt;
const PROC_PIDVNODEPATHINFO: c_int = 9;
const MAXPATHLEN: usize = 1024;
#[repr(C)]
#[derive(Default, Clone, Copy)]
struct VinfoStat {
vst_dev: u32,
vst_mode: u16,
vst_nlink: u16,
vst_ino: u64,
vst_uid: u32,
vst_gid: u32,
vst_atime: i64,
vst_atimensec: i64,
vst_mtime: i64,
vst_mtimensec: i64,
vst_ctime: i64,
vst_ctimensec: i64,
vst_birthtime: i64,
vst_birthtimensec: i64,
vst_size: i64,
vst_blocks: i64,
vst_blksize: i32,
vst_flags: u32,
vst_gen: u32,
vst_rdev: u32,
vst_qspare: [i64; 2],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct VnodeInfo {
vi_stat: VinfoStat,
vi_type: i32,
vi_pad: i32,
vi_fsid: [i32; 2],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct VnodeInfoPath {
vip_vi: VnodeInfo,
vip_path: [u8; MAXPATHLEN],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ProcVnodePathInfo {
pvi_cdir: VnodeInfoPath,
pvi_rdir: VnodeInfoPath,
}
unsafe extern "C" {
fn proc_pidinfo(
pid: c_int,
flavor: c_int,
arg: u64,
buffer: *mut c_void,
buffersize: c_int,
) -> c_int;
}
let mut info: ProcVnodePathInfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<ProcVnodePathInfo>() as c_int;
let ret = unsafe {
proc_pidinfo(
pid as c_int,
PROC_PIDVNODEPATHINFO,
0,
&mut info as *mut _ as *mut c_void,
size,
)
};
if ret <= 0 {
return None;
}
let path = &info.pvi_cdir.vip_path;
let len = path.iter().position(|&b| b == 0).unwrap_or(0);
if len == 0 {
return None;
}
Some(std::path::PathBuf::from(OsString::from_vec(
path[..len].to_vec(),
)))
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn cwd_of_pid(_pid: u32) -> Option<std::path::PathBuf> {
None
}
pub const fn cwd_is_observable() -> bool {
cfg!(any(target_os = "linux", target_os = "macos"))
}
#[cfg(any(target_os = "linux", test))]
pub(crate) fn parse_vm_rss_kb(status: &str) -> Option<u64> {
status
.lines()
.find_map(|l| l.strip_prefix("VmRSS:"))?
.split_whitespace()
.next()?
.parse()
.ok()
}
#[cfg(target_os = "linux")]
pub(crate) fn process_rss_kb(pid: u32) -> Option<u64> {
std::fs::read_to_string(format!("/proc/{pid}/status"))
.ok()
.as_deref()
.and_then(parse_vm_rss_kb)
}
#[cfg(target_os = "macos")]
pub(crate) fn process_rss_kb(pid: u32) -> Option<u64> {
let mut info: libc::proc_taskinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_taskinfo>() as libc::c_int;
let got = unsafe {
libc::proc_pidinfo(
pid as libc::c_int,
libc::PROC_PIDTASKINFO,
0,
(&raw mut info).cast(),
size,
)
};
if got != size {
return None;
}
Some(info.pti_resident_size / 1024)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn process_rss_kb(_pid: u32) -> Option<u64> {
None
}
#[cfg(target_os = "linux")]
pub(crate) fn foreground_group_of(pid: i32) -> Option<i32> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
parse_tpgid(&stat)
}
#[cfg(target_os = "macos")]
pub(crate) fn foreground_group_of(pid: i32) -> Option<i32> {
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
let got = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
0,
(&mut info as *mut libc::proc_bsdinfo).cast(),
size,
)
};
if got != size {
return None;
}
let tpgid = info.e_tpgid as i32;
(tpgid > 0).then_some(tpgid)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn foreground_group_of(_pid: i32) -> Option<i32> {
None
}
#[cfg(any(target_os = "linux", test))]
fn parse_tpgid(stat: &str) -> Option<i32> {
let rest = &stat[stat.rfind(')')? + 1..];
let tpgid: i32 = rest.split_whitespace().nth(5)?.parse().ok()?;
(tpgid > 0).then_some(tpgid)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tpgid_is_read_past_a_command_name_with_spaces_and_parens() {
let stat = "4242 (my (odd) sh) S 1 4242 4242 34816 5151 4194560 0 0";
assert_eq!(parse_tpgid(stat), Some(5151));
assert_eq!(
parse_tpgid("1 (init) S 0 1 1 0 -1 4194560"),
None,
"no terminal"
);
assert_eq!(parse_tpgid("garbage"), None);
}
#[test]
fn process_name_resolves_a_live_pid() {
let me = std::process::id() as i32;
let name = process_name(me);
assert!(
name.as_deref().is_some_and(|n| !n.is_empty()),
"the test process resolves to a non-empty name: {name:?}"
);
}
#[cfg(unix)]
#[test]
fn process_cmdline_reads_a_live_process_argv() {
let mut child = std::process::Command::new("sleep")
.arg("30")
.spawn()
.expect("sleep runs");
let mut argv = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(200),
"the child's argv to read as sleep's",
|| {
argv = process_cmdline(child.id() as i32);
argv.as_ref()
.is_some_and(|a| a.last().map(String::as_str) == Some("30"))
},
);
let _ = child.kill();
let _ = child.wait();
let argv = argv.expect("a live child's argv");
assert!(argv[0].ends_with("sleep"), "{argv:?}");
assert_eq!(argv.last().map(String::as_str), Some("30"), "{argv:?}");
}
#[test]
fn cwd_of_pid_on_self_returns_a_directory_under_tempdir() {
let pid = std::process::id();
match cwd_of_pid(pid) {
Some(p) => assert!(
p.is_dir(),
"cwd lookup must return a real directory, got {p:?}"
),
None => {
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn process_rss_kb_reads_current_process_on_linux_and_macos() {
let rss = process_rss_kb(std::process::id()).expect("current process RSS is readable");
assert!(rss > 0, "current process must have non-zero RSS, got {rss}");
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn foreground_group_of_reads_live_pty_session_leader() {
use portable_pty::{CommandBuilder, NativePtySystem, PtySize, PtySystem};
let pair = NativePtySystem::default()
.openpty(PtySize {
rows: 24,
cols: 80,
pixel_width: 0,
pixel_height: 0,
})
.expect("openpty");
let mut cmd = CommandBuilder::new("sh");
cmd.arg("-c");
cmd.arg("sleep 30");
let mut child = pair.slave.spawn_command(cmd).expect("spawn shell in pty");
drop(pair.slave);
let pid = child.process_id().expect("shell pid") as i32;
let mut tpgid = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"PTY session leader's foreground process group",
|| {
tpgid = foreground_group_of(pid);
tpgid.is_some()
},
);
let _ = child.kill();
let _ = child.wait();
assert!(
tpgid.is_some_and(|g| g > 0),
"foreground_group_of must resolve a live PTY session leader on Linux and macOS: {tpgid:?}"
);
}
}