@@ -7,6 +7,8 @@ use std::path::PathBuf;
77
88use clap:: { crate_version, Arg , ArgAction , ArgMatches , Command } ;
99use uu_pgrep:: process:: { walk_process, ProcessInformation } ;
10+ #[ cfg( unix) ]
11+ use uucore:: process:: geteuid;
1012use uucore:: { error:: UResult , format_usage, help_about, help_usage} ;
1113
1214const ABOUT : & str = help_about ! ( "pidof.md" ) ;
@@ -94,21 +96,35 @@ fn collect_matched_pids(matches: &ArgMatches) -> Vec<usize> {
9496 . copied ( )
9597 . collect :: < Vec < _ > > ( ) ;
9698
99+ // Original pidof silently ignores the check-root option if the user is not root.
100+ #[ cfg( unix) ]
101+ let check_root = matches. get_flag ( "check-root" ) && geteuid ( ) == 0 ;
102+ #[ cfg( not( unix) ) ]
103+ let check_root = false ;
104+ let our_root = ProcessInformation :: current_process_info ( )
105+ . unwrap ( )
106+ . root ( )
107+ . unwrap ( ) ;
108+
97109 program_names
98110 . into_iter ( )
99111 . flat_map ( |program| {
100112 let mut processed = Vec :: new ( ) ;
101113 for mut process in collected. clone ( ) {
102- let contains =
103- match_process_name ( & mut process, & program, with_workers, match_scripts) ;
104- let should_omit = arg_omit_pid. contains ( & process. pid ) ;
105-
106- if contains && !should_omit {
107- if matches. get_flag ( "t" ) {
108- processed. extend_from_slice ( & process. thread_ids ( ) ) ;
109- } else {
110- processed. push ( process. pid ) ;
111- }
114+ if !match_process_name ( & mut process, & program, with_workers, match_scripts) {
115+ continue ;
116+ }
117+ if arg_omit_pid. contains ( & process. pid ) {
118+ continue ;
119+ }
120+ if check_root && process. root ( ) . unwrap ( ) != our_root {
121+ continue ;
122+ }
123+
124+ if matches. get_flag ( "t" ) {
125+ processed. extend_from_slice ( & process. thread_ids ( ) ) ;
126+ } else {
127+ processed. push ( process. pid ) ;
112128 }
113129 }
114130
@@ -140,12 +156,13 @@ pub fn uu_app() -> Command {
140156 . index ( 1 )
141157 . action ( ArgAction :: Append ) ,
142158 )
143- // .arg(
144- // Arg::new("c")
145- // .short('c')
146- // .help("Return PIDs with the same root directory")
147- // .action(ArgAction::SetTrue),
148- // )
159+ . arg (
160+ Arg :: new ( "check-root" )
161+ . short ( 'c' )
162+ . long ( "check-root" )
163+ . help ( "Only return PIDs with the same root directory" )
164+ . action ( ArgAction :: SetTrue ) ,
165+ )
149166 . arg (
150167 Arg :: new ( "S" )
151168 . short ( 'S' )
0 commit comments