/contrib/cvs/lib/waitpid.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 80 lines · 69 code · 10 blank · 1 comment · 18 complexity · 21992f9d37417e8d3541185c63f09f0d MD5 · raw file

  1. #ifdef HAVE_CONFIG_H
  2. #include "config.h"
  3. #endif
  4. #include "system.h"
  5. #include "wait.h"
  6. #include <stdio.h>
  7. struct unreaped {
  8. pid_t pid;
  9. int status;
  10. };
  11. static struct unreaped *unreaped;
  12. static int n;
  13. static struct unreaped *ualloc (oldptr, n)
  14. struct unreaped *oldptr;
  15. int n;
  16. {
  17. n *= sizeof (struct unreaped);
  18. if (n == 0)
  19. n = 1;
  20. if (oldptr)
  21. oldptr = (struct unreaped *) realloc ((char *) oldptr, n);
  22. else
  23. oldptr = (struct unreaped *) malloc (n);
  24. if (oldptr == 0)
  25. {
  26. fprintf (stderr, "cannot allocate %d bytes\n", n);
  27. exit (1);
  28. }
  29. return oldptr;
  30. }
  31. pid_t waitpid (pid, status, options)
  32. pid_t pid;
  33. int *status;
  34. int options;
  35. {
  36. int i;
  37. /* initialize */
  38. if (unreaped == 0)
  39. {
  40. unreaped = ualloc (unreaped, 1);
  41. unreaped[0].pid = 0;
  42. n = 1;
  43. }
  44. for (i = 0; unreaped[i].pid; i++)
  45. if (unreaped[i].pid == pid)
  46. {
  47. *status = unreaped[i].status;
  48. while (unreaped[i].pid)
  49. {
  50. unreaped[i] = unreaped[i+1];
  51. i++;
  52. }
  53. n--;
  54. return pid;
  55. }
  56. while (1)
  57. {
  58. #ifdef HAVE_WAIT3
  59. pid_t p = wait3 (status, options, (struct rusage *) 0);
  60. #else
  61. pid_t p = wait (status);
  62. #endif
  63. if (p == 0 || p == -1 || p == pid)
  64. return p;
  65. n++;
  66. unreaped = ualloc (unreaped, n);
  67. unreaped[n-1].pid = p;
  68. unreaped[n-1].status = *status;
  69. }
  70. }