diff --git a/src/uu/pgrep/src/process.rs b/src/uu/pgrep/src/process.rs index 211f8a51..77634095 100644 --- a/src/uu/pgrep/src/process.rs +++ b/src/uu/pgrep/src/process.rs @@ -424,6 +424,8 @@ impl Namespace { pub struct ProcessInformation { pub pid: usize, pub cmdline: String, + /// The arguments from `/proc//cmdline`, as they are + pub cmdline_args: Vec, inner_status: String, inner_stat: String, @@ -469,14 +471,17 @@ impl ProcessInformation { .parse::() .map_err(|_| io::ErrorKind::InvalidData)? }; - let cmdline = fs::read_to_string(dir_append(value.clone(), "cmdline".into()))? - .replace('\0', " ") - .trim_end() - .into(); + let raw_cmdline = fs::read_to_string(dir_append(value.clone(), "cmdline".into()))?; + let cmdline = raw_cmdline.replace('\0', " ").trim_end().into(); + let cmdline_args = raw_cmdline + .split_terminator('\0') + .map(String::from) + .collect(); Ok(Self { pid, cmdline, + cmdline_args, inner_status: fs::read_to_string(dir_append(value.clone(), "status".into()))?, inner_stat: fs::read_to_string(dir_append(value, "stat".into()))?, ..Default::default() diff --git a/src/uu/pidof/src/pidof.rs b/src/uu/pidof/src/pidof.rs index 00069481..adc80f2b 100644 --- a/src/uu/pidof/src/pidof.rs +++ b/src/uu/pidof/src/pidof.rs @@ -3,6 +3,7 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. +use std::fs; use std::path::PathBuf; use clap::{crate_version, Arg, ArgAction, ArgMatches, Command}; @@ -50,8 +51,9 @@ fn match_process_name( with_workers: bool, match_scripts: bool, ) -> bool { - let binding = process.cmdline.split(' ').collect::>(); - let path = binding.first().unwrap().to_string(); + // name() needs &mut process, so keep owned copies of the two arguments used below. + let path = process.cmdline_args.first().cloned().unwrap_or_default(); + let script = process.cmdline_args.get(1).cloned(); if path.is_empty() { if !with_workers { @@ -60,15 +62,32 @@ fn match_process_name( return process.name().unwrap() == name_to_match; }; - if PathBuf::from(path).file_name().unwrap().to_str().unwrap() == name_to_match { + if PathBuf::from(&path).file_name().and_then(|f| f.to_str()) == Some(name_to_match) { + return true; + } + + // Like procps-ng, also match the executable, so a process started with + // another argv[0] (`exec -a`) is still found, also by the 15-byte name + // the kernel cuts it to. + if let Ok(exe) = fs::read_link(format!("/proc/{}/exe", process.pid)) { + if let Some(exe) = exe.file_name().and_then(|f| f.to_str()) { + if exe == name_to_match || exe.as_bytes().get(..15) == Some(name_to_match.as_bytes()) { + return true; + } + } + } + + // A process that rewrites its title, like "sshd: /usr/sbin/sshd -D", is + // matched by its process name too. + if path.contains(' ') && process.name().is_ok_and(|n| n == name_to_match) { return true; } // When a script (ie. file starting with e.g. #!/bin/sh) is run like `./script.sh`, then // its cmdline will look like `/bin/sh ./script.sh` but its .name() will be `script.sh`. // As name() gets truncated to 15 characters, the original pidof seems to always do a prefix match. - if match_scripts && binding.len() > 1 { - return PathBuf::from(binding[1]) + if let Some(script) = script.filter(|_| match_scripts) { + return PathBuf::from(&script) .file_name() .map(|f| f.to_str().unwrap()) .is_some_and(|f| f == name_to_match && f.starts_with(&process.name().unwrap())); diff --git a/tests/by-util/test_pidof.rs b/tests/by-util/test_pidof.rs index 3dc7059d..9f211142 100644 --- a/tests/by-util/test_pidof.rs +++ b/tests/by-util/test_pidof.rs @@ -158,3 +158,51 @@ fn test_script() { executed_via_sh_child.kill().unwrap(); executed_via_sh_child.wait().unwrap(); } + +#[test] +#[cfg(target_os = "linux")] +fn test_process_with_another_argv0() { + use std::os::unix::process::CommandExt; + + // A copy of the shell under its own name, so the executable and the + // process name are known. The name is longer than 15 bytes, so the + // kernel cuts the process name to "pidoftitletest-". + let temp_dir = tempfile::tempdir().unwrap(); + let program = temp_dir.path().join("pidoftitletest-long"); + std::fs::copy("/bin/sh", &program).unwrap(); + + for argv0 in ["pidoftitletest: worker process", "another-argv0"] { + // "; :" keeps the shell from replacing itself with sleep. Other tests + // forking while the copy was open for writing make exec fail with + // ETXTBSY for a moment, so retry that. + let mut child = (0..100) + .find_map(|_| { + match std::process::Command::new(&program) + .arg0(argv0) + .args(["-c", "sleep 5; :"]) + .process_group(0) + .spawn() + { + Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy => { + std::thread::sleep(std::time::Duration::from_millis(10)); + None + } + result => Some(result.unwrap()), + } + }) + .unwrap(); + std::thread::sleep(std::time::Duration::from_millis(200)); + + for name in ["pidoftitletest-long", "pidoftitletest-"] { + new_ucmd!() + .arg(name) + .succeeds() + .stdout_contains(child.id().to_string()); + } + new_ucmd!().arg("pidoftitletest:").fails(); + + // Kill the whole group, so the forked sleep goes too. + unsafe { uucore::libc::kill(-(child.id() as i32), uucore::libc::SIGKILL) }; + child.wait().unwrap(); + } +}