gravel_provider_kill/
linux.rs

1use anyhow::Result;
2use gravel_ffi::SimpleHit;
3use nix::sys::signal::{Signal, kill};
4use procfs::process::Process;
5
6pub type Pid = i32;
7
8pub fn kill_process(pid: Pid) -> Result<()> {
9	let pid = nix::unistd::Pid::from_raw(pid);
10
11	kill(pid, Signal::SIGKILL)?;
12	Ok(())
13}
14
15pub fn query() -> Result<impl Iterator<Item = SimpleHit>> {
16	let hits = procfs::process::all_processes()?
17		.filter_map(Result::ok)
18		.map(get_hit)
19		.filter_map(Result::ok);
20
21	Ok(hits)
22}
23
24fn get_hit(process: Process) -> Result<SimpleHit> {
25	let args = process.cmdline()?;
26	let cmdline = args.join(" ").replace('\n', "\\n");
27	let name = get_cmdline_binary(&args)
28		.or_else(|| get_exe_binary(&process))
29		.or_else(|| get_command_name(&process))
30		.unwrap_or_else(|| String::from("unknown process"));
31
32	Ok(super::get_hit(&name, process.pid, &cmdline))
33}
34
35fn get_cmdline_binary(args: &[String]) -> Option<String> {
36	args.first()?
37		.split(' ')
38		.next()?
39		.split('/')
40		.next_back()
41		.map(ToOwned::to_owned)
42}
43
44fn get_exe_binary(process: &Process) -> Option<String> {
45	let exe = process.exe().ok()?;
46
47	exe.file_name().map(|s| s.to_string_lossy().into_owned())
48}
49
50fn get_command_name(process: &Process) -> Option<String> {
51	process.stat().map(|s| format!("[{}]", s.comm)).ok()
52}