pgrep.cpp 1.6 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 <LibCore/System.h>
  11. #include <LibMain/Main.h>
  12. #include <LibRegex/Regex.h>
  13. ErrorOr<int> serenity_main(Main::Arguments args)
  14. {
  15. TRY(Core::System::pledge("stdio rpath"));
  16. TRY(Core::System::unveil("/sys/kernel/processes", "r"));
  17. TRY(Core::System::unveil("/etc/passwd", "r"));
  18. TRY(Core::System::unveil(nullptr, nullptr));
  19. bool case_insensitive = false;
  20. bool invert_match = false;
  21. char const* pattern = nullptr;
  22. Core::ArgsParser args_parser;
  23. args_parser.add_option(case_insensitive, "Make matches case-insensitive", nullptr, 'i');
  24. args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v');
  25. args_parser.add_positional_argument(pattern, "Process name to search for", "process-name");
  26. args_parser.parse(args);
  27. PosixOptions options {};
  28. if (case_insensitive)
  29. options |= PosixFlags::Insensitive;
  30. Regex<PosixExtended> re(pattern, options);
  31. if (re.parser_result.error != regex::Error::NoError) {
  32. return 1;
  33. }
  34. auto all_processes = TRY(Core::ProcessStatisticsReader::get_all());
  35. Vector<pid_t> matches;
  36. for (auto& it : all_processes.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. }