pgrep.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2021, Aziz Berkay Yesilyurt <abyesilyurt@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/Vector.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/ProcessStatisticsReader.h>
  10. #include <LibRegex/Regex.h>
  11. int main(int argc, char** argv)
  12. {
  13. if (pledge("stdio rpath", nullptr) < 0) {
  14. perror("pledge");
  15. return 1;
  16. }
  17. bool case_insensitive = false;
  18. bool invert_match = false;
  19. char const* pattern = nullptr;
  20. Core::ArgsParser args_parser;
  21. args_parser.add_option(case_insensitive, "Make matches case-insensitive", nullptr, 'i');
  22. args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v');
  23. args_parser.add_positional_argument(pattern, "Process name to search for", "process-name");
  24. args_parser.parse(argc, argv);
  25. PosixOptions options {};
  26. if (case_insensitive)
  27. options |= PosixFlags::Insensitive;
  28. Regex<PosixExtended> re(pattern, options);
  29. if (re.parser_result.error != Error::NoError) {
  30. return 1;
  31. }
  32. auto all_processes = Core::ProcessStatisticsReader::get_all();
  33. if (!all_processes.has_value())
  34. return 1;
  35. Vector<pid_t> matches;
  36. for (auto& it : all_processes.value().processes) {
  37. auto result = re.match(it.name, PosixFlags::Global);
  38. if (result.success ^ invert_match) {
  39. matches.append(it.pid);
  40. }
  41. }
  42. quick_sort(matches);
  43. for (auto& match : matches) {
  44. outln("{}", match);
  45. }
  46. return 0;
  47. }