pidof.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. static int pid_of(const String& process_name, bool single_shot, bool omit_pid, pid_t pid)
  14. {
  15. bool displayed_at_least_one = false;
  16. auto all_processes = Core::ProcessStatisticsReader::get_all();
  17. if (!all_processes.has_value())
  18. return 1;
  19. for (auto& it : all_processes.value().processes) {
  20. if (it.name == process_name) {
  21. if (!omit_pid || it.pid != pid) {
  22. out(displayed_at_least_one ? " {}" : "{}", it.pid);
  23. displayed_at_least_one = true;
  24. if (single_shot)
  25. break;
  26. }
  27. }
  28. }
  29. if (displayed_at_least_one)
  30. outln();
  31. return 0;
  32. }
  33. int main(int argc, char** argv)
  34. {
  35. bool single_shot = false;
  36. const char* omit_pid_value = nullptr;
  37. const char* process_name = nullptr;
  38. Core::ArgsParser args_parser;
  39. args_parser.add_option(single_shot, "Only return one pid", nullptr, 's');
  40. 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");
  41. args_parser.add_positional_argument(process_name, "Process name to search for", "process-name");
  42. args_parser.parse(argc, argv);
  43. pid_t pid_to_omit = 0;
  44. if (omit_pid_value) {
  45. if (!strcmp(omit_pid_value, "%PPID")) {
  46. pid_to_omit = getppid();
  47. } else {
  48. auto number = StringView(omit_pid_value).to_uint();
  49. if (!number.has_value()) {
  50. warnln("Invalid value for -o");
  51. args_parser.print_usage(stderr, argv[0]);
  52. return 1;
  53. }
  54. pid_to_omit = number.value();
  55. }
  56. }
  57. return pid_of(process_name, single_shot, omit_pid_value != nullptr, pid_to_omit);
  58. }