pidof.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * pidof implementation for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under the GPL version 2, see the file LICENSE in this tarball.
  8. */
  9. #include "libbb.h"
  10. enum {
  11. USE_FEATURE_PIDOF_SINGLE(OPTBIT_SINGLE,)
  12. USE_FEATURE_PIDOF_OMIT( OPTBIT_OMIT ,)
  13. OPT_SINGLE = USE_FEATURE_PIDOF_SINGLE((1<<OPTBIT_SINGLE)) + 0,
  14. OPT_OMIT = USE_FEATURE_PIDOF_OMIT( (1<<OPTBIT_OMIT )) + 0,
  15. };
  16. int pidof_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  17. int pidof_main(int argc ATTRIBUTE_UNUSED, char **argv)
  18. {
  19. unsigned first = 1;
  20. unsigned opt;
  21. #if ENABLE_FEATURE_PIDOF_OMIT
  22. char ppid_str[sizeof(int)*3 + 1];
  23. llist_t *omits = NULL; /* list of pids to omit */
  24. opt_complementary = "o::";
  25. #endif
  26. /* do unconditional option parsing */
  27. opt = getopt32(argv, ""
  28. USE_FEATURE_PIDOF_SINGLE ("s")
  29. USE_FEATURE_PIDOF_OMIT("o:", &omits));
  30. #if ENABLE_FEATURE_PIDOF_OMIT
  31. /* fill omit list. */
  32. {
  33. llist_t *omits_p = omits;
  34. while (omits_p) {
  35. /* are we asked to exclude the parent's process ID? */
  36. if (strcmp(omits_p->data, "%PPID") == 0) {
  37. sprintf(ppid_str, "%u", (unsigned)getppid());
  38. omits_p->data = ppid_str;
  39. }
  40. omits_p = omits_p->link;
  41. }
  42. }
  43. #endif
  44. /* Looks like everything is set to go. */
  45. argv += optind;
  46. while (*argv) {
  47. pid_t *pidList;
  48. pid_t *pl;
  49. /* reverse the pidlist like GNU pidof does. */
  50. pidList = pidlist_reverse(find_pid_by_name(*argv));
  51. for (pl = pidList; *pl; pl++) {
  52. #if ENABLE_FEATURE_PIDOF_OMIT
  53. if (opt & OPT_OMIT) {
  54. llist_t *omits_p = omits;
  55. while (omits_p) {
  56. if (xatoul(omits_p->data) == *pl) {
  57. goto omitting;
  58. }
  59. omits_p = omits_p->link;
  60. }
  61. }
  62. #endif
  63. printf(" %u" + first, (unsigned)*pl);
  64. first = 0;
  65. if (ENABLE_FEATURE_PIDOF_SINGLE && (opt & OPT_SINGLE))
  66. break;
  67. #if ENABLE_FEATURE_PIDOF_OMIT
  68. omitting: ;
  69. #endif
  70. }
  71. free(pidList);
  72. argv++;
  73. }
  74. if (!first)
  75. bb_putchar('\n');
  76. #if ENABLE_FEATURE_PIDOF_OMIT
  77. if (ENABLE_FEATURE_CLEAN_UP)
  78. llist_free(omits, NULL);
  79. #endif
  80. return first; /* 1 (failure) - no processes found */
  81. }