4
0

waitpid.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Emulate waitpid on systems that just have wait.
  2. Copyright 1994, 1995, 1998, 1999 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; see the file COPYING.
  13. If not, write to the Free Software Foundation,
  14. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  15. #if HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <errno.h>
  19. #ifndef errno
  20. extern int errno;
  21. #endif
  22. #define WAITPID_CHILDREN 8
  23. static pid_t waited_pid[WAITPID_CHILDREN];
  24. static int waited_status[WAITPID_CHILDREN];
  25. pid_t
  26. waitpid (pid_t pid, int *stat_loc, int options)
  27. {
  28. int i;
  29. pid_t p;
  30. if (!options && (pid == -1 || 0 < pid))
  31. {
  32. /* If we have already waited for this child, return it immediately. */
  33. for (i = 0; i < WAITPID_CHILDREN; i++)
  34. {
  35. p = waited_pid[i];
  36. if (p && (p == pid || pid == -1))
  37. {
  38. waited_pid[i] = 0;
  39. goto success;
  40. }
  41. }
  42. /* The child has not returned yet; wait for it, accumulating status. */
  43. for (i = 0; i < WAITPID_CHILDREN; i++)
  44. if (! waited_pid[i])
  45. {
  46. p = wait (&waited_status[i]);
  47. if (p < 0)
  48. return p;
  49. if (p == pid || pid == -1)
  50. goto success;
  51. waited_pid[i] = p;
  52. }
  53. }
  54. /* We cannot emulate this wait call, e.g. because of too many children. */
  55. errno = EINVAL;
  56. return -1;
  57. success:
  58. if (stat_loc)
  59. *stat_loc = waited_status[i];
  60. return p;
  61. }