Skip to content

Commit

Permalink
pidof: Support '-t' flag
Browse files Browse the repository at this point in the history
This flag makes pidof print thread ids of threads belonging to the
matching processes.
  • Loading branch information
dezgeg committed Feb 6, 2025
1 parent f934fa5 commit f95c6a4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
27 changes: 27 additions & 0 deletions src/uu/pgrep/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ pub struct ProcessInformation {
cached_stat: Option<Rc<Vec<String>>>,

cached_start_time: Option<u64>,

cached_thread_ids: Option<Rc<Vec<usize>>>,
}

impl ProcessInformation {
Expand Down Expand Up @@ -328,6 +330,31 @@ impl ProcessInformation {

Teletype::Unknown
}

pub fn thread_ids(&mut self) -> Rc<Vec<usize>> {
if let Some(c) = &self.cached_thread_ids {
return Rc::clone(c);
}

let tids_dir = format!("/proc/{}/task", self.pid);
let result = Rc::new(
WalkDir::new(tids_dir)
.min_depth(1)
.max_depth(1)
.follow_links(false)
.into_iter()
.flatten()
.flat_map(|it| {
it.path()
.file_name()
.map(|it| it.to_str().unwrap().parse::<usize>().unwrap())
})
.collect::<Vec<_>>(),
);

self.cached_thread_ids = Some(Rc::clone(&result));
Rc::clone(&result)
}
}
impl TryFrom<DirEntry> for ProcessInformation {
type Error = io::Error;
Expand Down
21 changes: 18 additions & 3 deletions src/uu/pidof/src/pidof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,23 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
};

let collected = collect_matched_pids(&matches);
let to_print = if matches.get_flag("t") {
collected
.into_iter()
.flat_map(|mut it| (*it.thread_ids()).clone())
.collect::<Vec<_>>()
} else {
collected.into_iter().map(|it| it.pid).collect::<Vec<_>>()
};

if collected.is_empty() {
if to_print.is_empty() {
uucore::error::set_exit_code(1);
return Ok(());
};

let output = collected
let output = to_print
.into_iter()
.map(|it| it.pid.to_string())
.map(|it| it.to_string())
.collect::<Vec<_>>()
.join(arg_separator);

Expand Down Expand Up @@ -164,6 +172,13 @@ pub fn uu_app() -> Command {
.help("Only return one PID")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("t")
.short('t')
.long("lightweight")
.help("Show thread ids instead of process ids")
.action(ArgAction::SetTrue),
)
// .arg(
// Arg::new("x")
// .short('x')
Expand Down

0 comments on commit f95c6a4

Please sign in to comment.