waitpid.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Emulate waitpid on systems that just have wait.
  2. Copyright 1994, 1995, 1998, 1999, 2007 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 3, 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. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  15. #if HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <errno.h>
  21. #ifndef errno
  22. extern int errno;
  23. #endif
  24. #define WAITPID_CHILDREN 8
  25. static pid_t waited_pid[WAITPID_CHILDREN];
  26. static int waited_status[WAITPID_CHILDREN];
  27. pid_t
  28. waitpid (pid_t pid, int *stat_loc, int options)
  29. {
  30. int i;
  31. pid_t p;
  32. if (!options && (pid == -1 || 0 < pid))
  33. {
  34. /* If we have already waited for this child, return it immediately. */
  35. for (i = 0; i < WAITPID_CHILDREN; i++)
  36. {
  37. p = waited_pid[i];
  38. if (p && (p == pid || pid == -1))
  39. {
  40. waited_pid[i] = 0;
  41. goto success;
  42. }
  43. }
  44. /* The child has not returned yet; wait for it, accumulating status. */
  45. for (i = 0; i < WAITPID_CHILDREN; i++)
  46. if (! waited_pid[i])
  47. {
  48. p = wait (&waited_status[i]);
  49. if (p < 0)
  50. return p;
  51. if (p == pid || pid == -1)
  52. goto success;
  53. waited_pid[i] = p;
  54. }
  55. }
  56. /* We cannot emulate this wait call, e.g. because of too many children. */
  57. errno = EINVAL;
  58. return -1;
  59. success:
  60. if (stat_loc)
  61. *stat_loc = waited_status[i];
  62. return p;
  63. }