find_pid_by_name.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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, see the file LICENSE in this tarball.
  8. */
  9. #include <stdio.h>
  10. #include <ctype.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include "libbb.h"
  14. /* find_pid_by_name()
  15. *
  16. * Modified by Vladimir Oleynik for use with libbb/procps.c
  17. * This finds the pid of the specified process.
  18. * Currently, it's implemented by rummaging through
  19. * the proc filesystem.
  20. *
  21. * Returns a list of all matching PIDs
  22. * It is the caller's duty to free the returned pidlist.
  23. */
  24. long* find_pid_by_name( const char* pidName)
  25. {
  26. long* pidList;
  27. int i=0;
  28. procps_status_t * p;
  29. pidList = xmalloc(sizeof(long));
  30. while ((p = procps_scan(0)) != 0)
  31. {
  32. if (strncmp(p->short_cmd, pidName, COMM_LEN-1) == 0) {
  33. pidList=xrealloc( pidList, sizeof(long) * (i+2));
  34. pidList[i++]=p->pid;
  35. }
  36. }
  37. pidList[i] = i==0 ? -1 : 0;
  38. return pidList;
  39. }
  40. long *pidlist_reverse(long *pidList)
  41. {
  42. int i=0;
  43. while (pidList[i] > 0 && ++i);
  44. if ( i-- > 0) {
  45. long k;
  46. int j;
  47. for (j = 0; i > j; i--, j++) {
  48. k = pidList[i];
  49. pidList[i] = pidList[j];
  50. pidList[j] = k;
  51. }
  52. }
  53. return pidList;
  54. }
  55. /* END CODE */
  56. /*
  57. Local Variables:
  58. c-file-style: "linux"
  59. c-basic-offset: 4
  60. tab-width: 4
  61. End:
  62. */