pgrep.cpp 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /*
  2. * Copyright (c) 2021, Aziz Berkay Yesilyurt <abyesilyurt@gmail.com>
  3. * Copyright (c) 2023, Tim Ledbetter <timledbetter@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <AK/Vector.h>
  9. #include <LibCore/Account.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/ProcessStatisticsReader.h>
  12. #include <LibCore/System.h>
  13. #include <LibMain/Main.h>
  14. #include <LibRegex/Regex.h>
  15. ErrorOr<int> serenity_main(Main::Arguments args)
  16. {
  17. TRY(Core::System::pledge("stdio rpath"));
  18. TRY(Core::System::unveil("/sys/kernel/processes", "r"));
  19. TRY(Core::System::unveil("/etc/group", "r"));
  20. TRY(Core::System::unveil("/etc/passwd", "r"));
  21. TRY(Core::System::unveil(nullptr, nullptr));
  22. bool display_number_of_matches = false;
  23. auto pid_delimiter = "\n"sv;
  24. bool case_insensitive = false;
  25. bool list_process_name = false;
  26. bool invert_match = false;
  27. bool exact_match = false;
  28. HashTable<uid_t> uids_to_filter_by;
  29. StringView pattern;
  30. Core::ArgsParser args_parser;
  31. args_parser.add_option(display_number_of_matches, "Suppress normal output and print the number of matching processes", "count", 'c');
  32. args_parser.add_option(pid_delimiter, "Set the string used to delimit multiple pids", "delimiter", 'd', nullptr);
  33. args_parser.add_option(case_insensitive, "Make matches case-insensitive", "ignore-case", 'i');
  34. args_parser.add_option(list_process_name, "List the process name in addition to its pid", "list-name", 'l');
  35. args_parser.add_option(Core::ArgsParser::Option {
  36. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  37. .help_string = "Select only processes whose UID is in the given comma-separated list. Login name or numerical user ID may be used",
  38. .long_name = "uid",
  39. .short_name = 'U',
  40. .value_name = "uid-list",
  41. .accept_value = [&uids_to_filter_by](StringView comma_separated_users) {
  42. for (auto user_string : comma_separated_users.split_view(',')) {
  43. auto maybe_uid = user_string.to_uint<uid_t>();
  44. if (maybe_uid.has_value()) {
  45. uids_to_filter_by.set(maybe_uid.value());
  46. } else {
  47. auto maybe_account = Core::Account::from_name(user_string, Core::Account::Read::PasswdOnly);
  48. if (maybe_account.is_error()) {
  49. warnln("Could not find user '{}': {}", user_string, maybe_account.error());
  50. return false;
  51. }
  52. uids_to_filter_by.set(maybe_account.release_value().uid());
  53. }
  54. }
  55. return true;
  56. },
  57. });
  58. args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v');
  59. args_parser.add_option(exact_match, "Select only processes whose names match the given pattern exactly", "exact", 'x');
  60. args_parser.add_positional_argument(pattern, "Process name to search for", "process-name");
  61. args_parser.parse(args);
  62. PosixOptions options {};
  63. if (case_insensitive)
  64. options |= PosixFlags::Insensitive;
  65. StringBuilder exact_pattern_builder;
  66. if (exact_match) {
  67. exact_pattern_builder.appendff("^({})$", pattern);
  68. pattern = exact_pattern_builder.string_view();
  69. }
  70. Regex<PosixExtended> re(pattern, options);
  71. if (re.parser_result.error != regex::Error::NoError) {
  72. return 1;
  73. }
  74. auto all_processes = TRY(Core::ProcessStatisticsReader::get_all());
  75. Vector<Core::ProcessStatistics> matches;
  76. for (auto const& it : all_processes.processes) {
  77. auto result = re.match(it.name, PosixFlags::Global);
  78. if (result.success ^ invert_match) {
  79. if (!uids_to_filter_by.is_empty() && !uids_to_filter_by.contains(it.uid))
  80. continue;
  81. matches.append(it);
  82. }
  83. }
  84. if (display_number_of_matches) {
  85. outln("{}", matches.size());
  86. } else {
  87. quick_sort(matches, [](auto const& a, auto const& b) { return a.pid < b.pid; });
  88. auto displayed_at_least_one = false;
  89. for (auto& match : matches) {
  90. if (displayed_at_least_one)
  91. out("{}"sv, pid_delimiter);
  92. out("{}"sv, match.pid);
  93. if (list_process_name)
  94. out(" {}"sv, match.name);
  95. displayed_at_least_one = true;
  96. }
  97. if (displayed_at_least_one)
  98. outln();
  99. }
  100. return matches.size() > 0 ? 0 : 1;
  101. }