Imported Upstream version 4.5.14
[platform/upstream/findutils.git] / lib / waitpid.c
1 /* Emulate waitpid on systems that just have wait.
2    Copyright 1994, 1995, 1998, 1999, 2010, 2011 Free Software
3    Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /* config.h must always be included first. */
20 #include <config.h>
21
22 /* system headers. */
23 #include <errno.h>
24
25
26 /* TODO: replace this with gnulib's waitpid. */
27 #if defined _MSC_VER || defined __MINGW32__
28 /* Native Woe32 API.  */
29 #include <process.h>
30 #else
31 /* Unix API.  */
32 #include <sys/wait.h>
33 #endif
34
35 #define WAITPID_CHILDREN 8
36 static pid_t waited_pid[WAITPID_CHILDREN];
37 static int waited_status[WAITPID_CHILDREN];
38
39 pid_t
40 waitpid (pid_t pid, int *stat_loc, int options)
41 {
42   int i;
43   pid_t p;
44
45   if (!options && (pid == -1 || 0 < pid))
46     {
47       /* If we have already waited for this child, return it immediately.  */
48       for (i = 0;  i < WAITPID_CHILDREN;  i++)
49         {
50           p = waited_pid[i];
51           if (p && (p == pid || pid == -1))
52             {
53               waited_pid[i] = 0;
54               goto success;
55             }
56         }
57
58       /* The child has not returned yet; wait for it, accumulating status.  */
59       for (i = 0;  i < WAITPID_CHILDREN;  i++)
60         if (! waited_pid[i])
61           {
62             p = wait (&waited_status[i]);
63             if (p < 0)
64               return p;
65             if (p == pid || pid == -1)
66               goto success;
67             waited_pid[i] = p;
68           }
69     }
70
71   /* We cannot emulate this wait call, e.g. because of too many children.  */
72   errno = EINVAL;
73   return -1;
74
75 success:
76   if (stat_loc)
77     *stat_loc = waited_status[i];
78   return p;
79 }