find_pid_by_name.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  8. */
  9. #include "libbb.h"
  10. /* find_pid_by_name()
  11. *
  12. * Modified by Vladimir Oleynik for use with libbb/procps.c
  13. * This finds the pid of the specified process.
  14. * Currently, it's implemented by rummaging through
  15. * the proc filesystem.
  16. *
  17. * Returns a list of all matching PIDs
  18. * It is the caller's duty to free the returned pidlist.
  19. */
  20. pid_t* find_pid_by_name(const char* procName)
  21. {
  22. pid_t* pidList;
  23. int i = 0;
  24. procps_status_t* p = NULL;
  25. pidList = xmalloc(sizeof(*pidList));
  26. while ((p = procps_scan(p, PSSCAN_PID|PSSCAN_COMM))) {
  27. if (strncmp(p->comm, procName, sizeof(p->comm)-1) == 0) {
  28. pidList = xrealloc(pidList, sizeof(*pidList) * (i+2));
  29. pidList[i++] = p->pid;
  30. }
  31. }
  32. pidList[i] = 0;
  33. return pidList;
  34. }
  35. pid_t *pidlist_reverse(pid_t *pidList)
  36. {
  37. int i = 0;
  38. while (pidList[i])
  39. i++;
  40. if (--i >= 0) {
  41. pid_t k;
  42. int j;
  43. for (j = 0; i > j; i--, j++) {
  44. k = pidList[i];
  45. pidList[i] = pidList[j];
  46. pidList[j] = k;
  47. }
  48. }
  49. return pidList;
  50. }