pidof.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 GPLv2, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. enum {
  11. IF_FEATURE_PIDOF_SINGLE(OPTBIT_SINGLE,)
  12. IF_FEATURE_PIDOF_OMIT( OPTBIT_OMIT ,)
  13. OPT_SINGLE = IF_FEATURE_PIDOF_SINGLE((1<<OPTBIT_SINGLE)) + 0,
  14. OPT_OMIT = IF_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 UNUSED_PARAM, char **argv)
  18. {
  19. unsigned first = 1;
  20. unsigned opt;
  21. #if ENABLE_FEATURE_PIDOF_OMIT
  22. llist_t *omits = NULL; /* list of pids to omit */
  23. opt_complementary = "o::";
  24. #endif
  25. /* do unconditional option parsing */
  26. opt = getopt32(argv, ""
  27. IF_FEATURE_PIDOF_SINGLE ("s")
  28. IF_FEATURE_PIDOF_OMIT("o:", &omits));
  29. #if ENABLE_FEATURE_PIDOF_OMIT
  30. /* fill omit list. */
  31. {
  32. llist_t *omits_p = omits;
  33. while (1) {
  34. omits_p = llist_find_str(omits_p, "%PPID");
  35. if (!omits_p)
  36. break;
  37. /* are we asked to exclude the parent's process ID? */
  38. omits_p->data = utoa((unsigned)getppid());
  39. }
  40. }
  41. #endif
  42. /* Looks like everything is set to go. */
  43. argv += optind;
  44. while (*argv) {
  45. pid_t *pidList;
  46. pid_t *pl;
  47. /* reverse the pidlist like GNU pidof does. */
  48. pidList = pidlist_reverse(find_pid_by_name(*argv));
  49. for (pl = pidList; *pl; pl++) {
  50. #if ENABLE_FEATURE_PIDOF_OMIT
  51. if (opt & OPT_OMIT) {
  52. llist_t *omits_p = omits;
  53. while (omits_p) {
  54. if (xatoul(omits_p->data) == (unsigned long)(*pl)) {
  55. goto omitting;
  56. }
  57. omits_p = omits_p->link;
  58. }
  59. }
  60. #endif
  61. printf(" %u" + first, (unsigned)*pl);
  62. first = 0;
  63. if (ENABLE_FEATURE_PIDOF_SINGLE && (opt & OPT_SINGLE))
  64. break;
  65. #if ENABLE_FEATURE_PIDOF_OMIT
  66. omitting: ;
  67. #endif
  68. }
  69. free(pidList);
  70. argv++;
  71. }
  72. if (!first)
  73. bb_putchar('\n');
  74. #if ENABLE_FEATURE_PIDOF_OMIT
  75. if (ENABLE_FEATURE_CLEAN_UP)
  76. llist_free(omits, NULL);
  77. #endif
  78. return first; /* 1 (failure) - no processes found */
  79. }