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