Skip to content

Commit 711d1b6

Browse files
pgrep: compare --older with the process's age (#821)
* pgrep: compare --older with the process's age The start time in /proc/<pid>/stat counts clock ticks since boot, so comparing it with the --older seconds matched nearly every process. Compare the time since the process started instead. * pgrep: read the uptime through uucore and report when it fails * pgrep: move the uptime import out of the unix-only block * pgrep: keep the fraction of the uptime for --older uucore's get_uptime returns whole seconds, so a process could look up to a second younger than it is and a 1.1 second old process did not match --older 1. Read /proc/uptime with its fraction, as procps-ng does, and still report an error when it can't be read.
1 parent 04a50aa commit 711d1b6

2 files changed

Lines changed: 64 additions & 2 deletions

File tree

‎src/uu/pgrep/src/process_matcher.rs‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,32 @@ fn get_namespaces(_pid: usize, _list: Option<Vec<&str>>) -> UResult<Namespace> {
242242
Ok(Namespace::new())
243243
}
244244

245+
/// The unit of a process's start time in /proc/<pid>/stat.
246+
#[cfg(unix)]
247+
fn clock_ticks_per_second() -> u64 {
248+
// SAFETY: sysconf has no preconditions.
249+
unsafe { uucore::libc::sysconf(uucore::libc::_SC_CLK_TCK) as u64 }
250+
}
251+
252+
// No process is listed on these platforms, so no start time gets compared.
253+
#[cfg(not(unix))]
254+
fn clock_ticks_per_second() -> u64 {
255+
1
256+
}
257+
258+
/// Return the time since boot in clock ticks.
259+
///
260+
/// `uucore::uptime::get_uptime` drops the fraction of a second, which makes a
261+
/// process look up to a second younger than it is. Read /proc/uptime with its
262+
/// fraction instead, as procps-ng does.
263+
fn uptime_ticks() -> UResult<u64> {
264+
let uptime = std::fs::read_to_string("/proc/uptime")
265+
.ok()
266+
.and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
267+
.ok_or_else(|| USimpleError::new(1, "could not read the system uptime"))?;
268+
Ok((uptime * clock_ticks_per_second() as f64) as u64)
269+
}
270+
245271
/// Collect pids with filter construct from command line arguments
246272
fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>> {
247273
// Filtration general parameters
@@ -260,6 +286,17 @@ fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>>
260286
HashSet::from([our_pid])
261287
};
262288

289+
// --older compares a process's age with the given seconds.
290+
let older_than_ticks = settings
291+
.older
292+
.map(|secs| -> UResult<(u64, u64)> {
293+
Ok((
294+
uptime_ticks()?,
295+
secs.saturating_mul(clock_ticks_per_second()),
296+
))
297+
})
298+
.transpose()?;
299+
263300
let pid_from_pidfile = settings
264301
.pidfile
265302
.as_ref()
@@ -299,8 +336,10 @@ fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>>
299336

300337
let tty_matched = any_matches(&settings.terminal, pid.tty());
301338

302-
let arg_older = settings.older.unwrap_or(0);
303-
let older_matched = pid.start_time().unwrap() >= arg_older;
339+
let older_matched = match older_than_ticks {
340+
Some((now, min_age)) => now.saturating_sub(pid.start_time().unwrap()) >= min_age,
341+
None => true,
342+
};
304343

305344
let parent_matched = any_matches(&settings.parent, pid.ppid().unwrap());
306345
let pgroup_matched = any_matches(&settings.pgroup, pid.pgid().unwrap());

‎tests/by-util/test_pgrep.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,29 @@ fn test_older_non_matching_pattern() {
131131
.no_stdout();
132132
}
133133

134+
#[test]
135+
#[cfg(target_os = "linux")]
136+
fn test_older_compares_process_age() {
137+
let mut child = Command::new("sleep").arg("10").spawn().unwrap();
138+
let pid = child.id().to_string();
139+
let parent = std::process::id().to_string();
140+
std::thread::sleep(std::time::Duration::from_millis(1500));
141+
142+
// A process 1.5 seconds old is older than 1 second, but not 5 seconds.
143+
// Other tests may have sleep children too, so only look for this one.
144+
let result = new_ucmd!()
145+
.args(&["--older", "1", "--parent", &parent, "-x", "sleep"])
146+
.succeeds();
147+
assert!(result.stdout_str().lines().any(|line| line == pid));
148+
let result = new_ucmd!()
149+
.args(&["--older", "5", "--parent", &parent, "-x", "sleep"])
150+
.run();
151+
assert!(!result.stdout_str().lines().any(|line| line == pid));
152+
153+
child.kill().unwrap();
154+
child.wait().unwrap();
155+
}
156+
134157
#[test]
135158
#[cfg(target_os = "linux")]
136159
fn test_full() {

0 commit comments

Comments
 (0)