From 9537be93bdc73978a62327958530760832a47ccc Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Tue, 20 Oct 2026 04:35:17 +0530 Subject: [PATCH 1/3] pidof: match processes by executable and by rewritten titles pidof took argv[0] as the first space-separated word of the joined command line. Servers that rewrite their title, like "sshd: /usr/sbin/sshd -D [listener]", came out as "sshd:", so "pidof sshd" found nothing, while "pidof sshd:" matched. A process started with another argv[0] (exec -a) was not found by its program name either. Match like procps-ng: the base name of the whole argv[0], the base name of /proc/PID/exe (also cut to the 15 bytes the kernel keeps), or, when argv[0] has a space in it, the process name. --- src/uu/pidof/src/pidof.rs | 34 +++++++++++++++++++++++++---- tests/by-util/test_pidof.rs | 43 +++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/uu/pidof/src/pidof.rs b/src/uu/pidof/src/pidof.rs index 00069481..6b005101 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,16 @@ fn match_process_name( with_workers: bool, match_scripts: bool, ) -> bool { - let binding = process.cmdline.split(' ').collect::>(); - let path = binding.first().unwrap().to_string(); + // `cmdline` has the arguments joined with spaces, so read them again to + // get argv[0] as it is. + let Ok(raw) = fs::read(format!("/proc/{}/cmdline", process.pid)) else { + return false; + }; + let binding = raw + .split(|&b| b == 0) + .map(String::from_utf8_lossy) + .collect::>(); + let path = binding.first().map(|it| it.to_string()).unwrap_or_default(); if path.is_empty() { if !with_workers { @@ -60,7 +69,24 @@ 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().unwrap() == name_to_match { return true; } @@ -68,7 +94,7 @@ fn match_process_name( // 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]) + return PathBuf::from(binding[1].as_ref()) .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..07622237 100644 --- a/tests/by-util/test_pidof.rs +++ b/tests/by-util/test_pidof.rs @@ -158,3 +158,46 @@ 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. + let temp_dir = tempfile::tempdir().unwrap(); + let program = temp_dir.path().join("pidoftitletest"); + 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; :"]) + .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)); + + new_ucmd!() + .arg("pidoftitletest") + .succeeds() + .stdout_contains(child.id().to_string()); + new_ucmd!().arg("pidoftitletest:").fails(); + + child.kill().unwrap(); + child.wait().unwrap(); + } +} From 0308dbc6874a59c406dd42e6f7986f7264d838f8 Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:17:40 +0530 Subject: [PATCH 2/3] pidof: reuse cmdline args from ProcessInformation, cover 15-byte name Keep the raw cmdline arguments in ProcessInformation so pidof does not read /proc//cmdline a second time, drop a new unwrap, test the 15-byte truncated name and kill the test's process group so the forked sleep does not linger. --- src/uu/pgrep/src/process.rs | 13 +++++++++---- src/uu/pidof/src/pidof.rs | 16 ++++------------ tests/by-util/test_pidof.rs | 19 ++++++++++++------- 3 files changed, 25 insertions(+), 23 deletions(-) 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 6b005101..ff7c25fb 100644 --- a/src/uu/pidof/src/pidof.rs +++ b/src/uu/pidof/src/pidof.rs @@ -51,16 +51,8 @@ fn match_process_name( with_workers: bool, match_scripts: bool, ) -> bool { - // `cmdline` has the arguments joined with spaces, so read them again to - // get argv[0] as it is. - let Ok(raw) = fs::read(format!("/proc/{}/cmdline", process.pid)) else { - return false; - }; - let binding = raw - .split(|&b| b == 0) - .map(String::from_utf8_lossy) - .collect::>(); - let path = binding.first().map(|it| it.to_string()).unwrap_or_default(); + let binding = process.cmdline_args.clone(); + let path = binding.first().cloned().unwrap_or_default(); if path.is_empty() { if !with_workers { @@ -86,7 +78,7 @@ fn match_process_name( // A process that rewrites its title, like "sshd: /usr/sbin/sshd -D", is // matched by its process name too. - if path.contains(' ') && process.name().unwrap() == name_to_match { + if path.contains(' ') && process.name().is_ok_and(|n| n == name_to_match) { return true; } @@ -94,7 +86,7 @@ fn match_process_name( // 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].as_ref()) + return PathBuf::from(&binding[1]) .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 07622237..9f211142 100644 --- a/tests/by-util/test_pidof.rs +++ b/tests/by-util/test_pidof.rs @@ -165,9 +165,10 @@ 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. + // 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"); + let program = temp_dir.path().join("pidoftitletest-long"); std::fs::copy("/bin/sh", &program).unwrap(); for argv0 in ["pidoftitletest: worker process", "another-argv0"] { @@ -179,6 +180,7 @@ fn test_process_with_another_argv0() { 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 => { @@ -191,13 +193,16 @@ fn test_process_with_another_argv0() { .unwrap(); std::thread::sleep(std::time::Duration::from_millis(200)); - new_ucmd!() - .arg("pidoftitletest") - .succeeds() - .stdout_contains(child.id().to_string()); + for name in ["pidoftitletest-long", "pidoftitletest-"] { + new_ucmd!() + .arg(name) + .succeeds() + .stdout_contains(child.id().to_string()); + } new_ucmd!().arg("pidoftitletest:").fails(); - child.kill().unwrap(); + // Kill the whole group, so the forked sleep goes too. + unsafe { uucore::libc::kill(-(child.id() as i32), uucore::libc::SIGKILL) }; child.wait().unwrap(); } } From cceb09b4cccaf91d644f869f8bb6054828097f06 Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:16:46 +0530 Subject: [PATCH 3/3] pidof: copy only the two arguments it needs instead of cmdline_args --- src/uu/pidof/src/pidof.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/uu/pidof/src/pidof.rs b/src/uu/pidof/src/pidof.rs index ff7c25fb..adc80f2b 100644 --- a/src/uu/pidof/src/pidof.rs +++ b/src/uu/pidof/src/pidof.rs @@ -51,8 +51,9 @@ fn match_process_name( with_workers: bool, match_scripts: bool, ) -> bool { - let binding = process.cmdline_args.clone(); - let path = binding.first().cloned().unwrap_or_default(); + // 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 { @@ -85,8 +86,8 @@ fn match_process_name( // 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()));