pidof.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/ProcessStatisticsReader.h>
  9. #include <LibCore/System.h>
  10. #include <LibMain/Main.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. static ErrorOr<int> pid_of(String const& process_name, bool single_shot, bool omit_pid, pid_t pid)
  16. {
  17. bool displayed_at_least_one = false;
  18. auto all_processes = Core::ProcessStatisticsReader::get_all();
  19. if (!all_processes.has_value())
  20. return 1;
  21. for (auto& it : all_processes.value().processes) {
  22. if (it.name == process_name) {
  23. if (!omit_pid || it.pid != pid) {
  24. out(displayed_at_least_one ? " {}"sv : "{}"sv, it.pid);
  25. displayed_at_least_one = true;
  26. if (single_shot)
  27. break;
  28. }
  29. }
  30. }
  31. if (displayed_at_least_one)
  32. outln();
  33. return 0;
  34. }
  35. ErrorOr<int> serenity_main(Main::Arguments args)
  36. {
  37. TRY(Core::System::pledge("stdio rpath"));
  38. TRY(Core::System::unveil("/sys/kernel/processes", "r"));
  39. TRY(Core::System::unveil("/etc/passwd", "r"));
  40. TRY(Core::System::unveil(nullptr, nullptr));
  41. bool single_shot = false;
  42. char const* omit_pid_value = nullptr;
  43. char const* process_name = nullptr;
  44. Core::ArgsParser args_parser;
  45. args_parser.add_option(single_shot, "Only return one pid", nullptr, 's');
  46. args_parser.add_option(omit_pid_value, "Omit the given PID, or the parent process if the special value %PPID is passed", nullptr, 'o', "pid");
  47. args_parser.add_positional_argument(process_name, "Process name to search for", "process-name");
  48. args_parser.parse(args);
  49. pid_t pid_to_omit = 0;
  50. if (omit_pid_value) {
  51. if (!strcmp(omit_pid_value, "%PPID")) {
  52. pid_to_omit = getppid();
  53. } else {
  54. auto number = StringView { omit_pid_value, strlen(omit_pid_value) }.to_uint();
  55. if (!number.has_value()) {
  56. warnln("Invalid value for -o");
  57. args_parser.print_usage(stderr, args.argv[0]);
  58. return 1;
  59. }
  60. pid_to_omit = number.value();
  61. }
  62. }
  63. return pid_of(process_name, single_shot, omit_pid_value != nullptr, pid_to_omit);
  64. }