Files
local-mini-kms/src/proc.rs
2022-07-29 00:35:05 +08:00

49 lines
1.6 KiB
Rust

#[cfg(not(target_os = "linux"))]
pub fn get_process(_port: u16) -> Option<(i32, String)> {
None
}
#[cfg(target_os = "linux")]
pub fn get_process(port: u16) -> Option<(i32, String)> {
let all_procs = match procfs::process::all_processes() {
Error(e) => {
rust_util::warning!("Get procfs all processes failed: {}", e);
return None;
}
Ok(all_procs) => all_procs,
};
let mut map: std::collections::HashMap<u64, procfs::process::Stat> = std::collections::HashMap::new();
for p in all_procs {
if let Ok(process) = p {
if let (Ok(stat), Ok(fds)) = (process.stat(), process.fd()) {
for fd in fds {
if let Ok(fd) = fd {
if let procfs::process::FDTarget::Socket(inode) = fd.target {
map.insert(inode, stat.clone());
}
}
}
}
}
}
let tcp = match procfs::net::tcp() {
Error(e) => {
rust_util::warning!("Get procfs net tcp failed: {}", e);
return None;
}
Ok(tcp) => tcp,
};
for entry in tcp.into_iter() {
if port == entry.local_address.port() {
if let Some(stat) = map.get(&entry.inode) {
return Some((stat.pid, stat.comm));
} else {
rust_util::warning!("Cannot get process by port: {}, inode: {}", port, entry.inode);
return None;
}
}
}
rust_util::warning!("Port not found: {}", port);
None
}