Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions src/uu/pgrep/src/process_matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,32 @@ fn get_namespaces(_pid: usize, _list: Option<Vec<&str>>) -> UResult<Namespace> {
Ok(Namespace::new())
}

/// The unit of a process's start time in /proc/<pid>/stat.
#[cfg(unix)]
fn clock_ticks_per_second() -> u64 {
// SAFETY: sysconf has no preconditions.
unsafe { uucore::libc::sysconf(uucore::libc::_SC_CLK_TCK) as u64 }
}

// No process is listed on these platforms, so no start time gets compared.
#[cfg(not(unix))]
fn clock_ticks_per_second() -> u64 {
1
}

/// Return the time since boot in clock ticks.
///
/// `uucore::uptime::get_uptime` drops the fraction of a second, which makes a
/// process look up to a second younger than it is. Read /proc/uptime with its
/// fraction instead, as procps-ng does.
fn uptime_ticks() -> UResult<u64> {
let uptime = std::fs::read_to_string("/proc/uptime")
.ok()
.and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
.ok_or_else(|| USimpleError::new(1, "could not read the system uptime"))?;
Ok((uptime * clock_ticks_per_second() as f64) as u64)
}

/// Collect pids with filter construct from command line arguments
fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>> {
// Filtration general parameters
Expand All @@ -260,6 +286,17 @@ fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>>
HashSet::from([our_pid])
};

// --older compares a process's age with the given seconds.
let older_than_ticks = settings
.older
.map(|secs| -> UResult<(u64, u64)> {
Ok((
uptime_ticks()?,
secs.saturating_mul(clock_ticks_per_second()),
))
})
.transpose()?;

let pid_from_pidfile = settings
.pidfile
.as_ref()
Expand Down Expand Up @@ -299,8 +336,10 @@ fn collect_matched_pids(settings: &Settings) -> UResult<Vec<ProcessInformation>>

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

let arg_older = settings.older.unwrap_or(0);
let older_matched = pid.start_time().unwrap() >= arg_older;
let older_matched = match older_than_ticks {
Some((now, min_age)) => now.saturating_sub(pid.start_time().unwrap()) >= min_age,
None => true,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why only linux? before this, --older wasn't gated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No good reason, I removed the Linux gates. Only the tick lookup keeps a cfg(unix), because sysconf is unix-only.

let parent_matched = any_matches(&settings.parent, pid.ppid().unwrap());
let pgroup_matched = any_matches(&settings.pgroup, pid.pgid().unwrap());
Expand Down
23 changes: 23 additions & 0 deletions tests/by-util/test_pgrep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ fn test_older_non_matching_pattern() {
.no_stdout();
}

#[test]
#[cfg(target_os = "linux")]
fn test_older_compares_process_age() {
let mut child = Command::new("sleep").arg("10").spawn().unwrap();
let pid = child.id().to_string();
let parent = std::process::id().to_string();
std::thread::sleep(std::time::Duration::from_millis(1500));

// A process 1.5 seconds old is older than 1 second, but not 5 seconds.
// Other tests may have sleep children too, so only look for this one.
let result = new_ucmd!()
.args(&["--older", "1", "--parent", &parent, "-x", "sleep"])
.succeeds();
assert!(result.stdout_str().lines().any(|line| line == pid));
let result = new_ucmd!()
.args(&["--older", "5", "--parent", &parent, "-x", "sleep"])
.run();
assert!(!result.stdout_str().lines().any(|line| line == pid));

child.kill().unwrap();
child.wait().unwrap();
}

#[test]
#[cfg(target_os = "linux")]
fn test_full() {
Expand Down
Loading