2019-05-13 12:31:23 +00:00
# include <AK/AKString.h>
2019-05-16 16:47:47 +00:00
# include <AK/HashMap.h>
2019-06-07 09:49:31 +00:00
# include <AK/Vector.h>
# include <LibCore/CArgsParser.h>
# include <LibCore/CProcessStatisticsReader.h>
# include <signal.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
2019-05-13 12:31:23 +00:00
static int pid_of ( const String & process_name , bool single_shot , bool omit_pid , pid_t pid )
{
bool displayed_at_least_one = false ;
2019-05-16 16:47:47 +00:00
HashMap < pid_t , CProcessStatistics > processes = CProcessStatisticsReader ( ) . get_map ( ) ;
2019-06-07 09:49:31 +00:00
2019-05-16 16:47:47 +00:00
for ( auto & it : processes ) {
2019-06-07 09:49:31 +00:00
if ( it . value . name = = process_name ) {
2019-05-16 16:47:47 +00:00
if ( ! omit_pid | | ( omit_pid & & it . value . pid ! = pid ) ) {
printf ( " %d " , it . value . pid ) ;
displayed_at_least_one = true ;
2019-05-13 12:31:23 +00:00
2019-05-16 16:47:47 +00:00
if ( single_shot )
break ;
}
}
2019-05-13 12:31:23 +00:00
}
if ( displayed_at_least_one )
2019-05-16 16:47:47 +00:00
printf ( " \n " ) ;
2019-05-13 12:31:23 +00:00
return 0 ;
}
int main ( int argc , char * * argv )
{
2019-05-17 13:35:30 +00:00
CArgsParser args_parser ( " pidof " ) ;
2019-05-17 10:51:44 +00:00
args_parser . add_arg ( " s " , " Single shot - this instructs the program to only return one pid " ) ;
args_parser . add_arg ( " o " , " pid " , " Tells pidof to omit processes with that pid. The special pid %PPID can be used to name the parent process of the pidof program. " ) ;
2019-06-22 13:47:08 +00:00
CArgsParserResult args = args_parser . parse ( argc , argv ) ;
2019-06-07 09:49:31 +00:00
2019-05-13 12:31:23 +00:00
bool s_arg = args . is_present ( " s " ) ;
bool o_arg = args . is_present ( " o " ) ;
pid_t pid = 0 ;
2019-06-07 09:49:31 +00:00
2019-05-13 12:31:23 +00:00
if ( o_arg ) {
bool ok = false ;
String pid_str = args . get ( " o " ) ;
2019-05-16 16:47:47 +00:00
if ( pid_str = = " %PPID " )
pid = getppid ( ) ;
else
pid = pid_str . to_uint ( ok ) ;
2019-05-13 12:31:23 +00:00
}
2019-06-07 09:49:31 +00:00
2019-05-13 12:31:23 +00:00
// We should have one single value : the process name
Vector < String > values = args . get_single_values ( ) ;
if ( values . size ( ) = = 0 ) {
2019-05-16 16:47:47 +00:00
args_parser . print_usage ( ) ;
2019-05-13 12:31:23 +00:00
return 0 ;
}
2019-06-07 09:49:31 +00:00
2019-05-13 12:31:23 +00:00
return pid_of ( values [ 0 ] , s_arg , o_arg , pid ) ;
}