Use waitid if possible.
[gnulib.git] / lib / wait-process.c
1 /* Waiting for a subprocess to finish.
2    Copyright (C) 2001-2003 Free Software Foundation, Inc.
3    Written by Bruno Haible <haible@clisp.cons.org>, 2001.
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 2, or (at your option)
8    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, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 /* Specification.  */
25 #include "wait-process.h"
26
27 #include <errno.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <signal.h>
31
32 #include <sys/types.h>
33
34 #if defined _MSC_VER || defined __MINGW32__
35
36 /* Native Woe32 API.  */
37 #include <process.h>
38 #define waitpid(pid,statusp,options) _cwait (statusp, pid, WAIT_CHILD)
39 #define WAIT_T int
40 #define WTERMSIG(x) ((x) & 0xff) /* or: SIGABRT ?? */
41 #define WCOREDUMP(x) 0
42 #define WEXITSTATUS(x) (((x) >> 8) & 0xff) /* or: (x) ?? */
43 #define WIFSIGNALED(x) (WTERMSIG (x) != 0) /* or: ((x) == 3) ?? */
44 #define WIFEXITED(x) (WTERMSIG (x) == 0) /* or: ((x) != 3) ?? */
45 #define WIFSTOPPED(x) 0
46
47 #else
48
49 /* Unix API.  */
50 #include <sys/wait.h>
51 /* On Linux, WEXITSTATUS are bits 15..8 and WTERMSIG are bits 7..0, while
52    BeOS uses the contrary.  Therefore we use the abstract macros.  */
53 #if HAVE_UNION_WAIT
54 # define WAIT_T union wait
55 # ifndef WTERMSIG
56 #  define WTERMSIG(x) ((x).w_termsig)
57 # endif
58 # ifndef WCOREDUMP
59 #  define WCOREDUMP(x) ((x).w_coredump)
60 # endif
61 # ifndef WEXITSTATUS
62 #  define WEXITSTATUS(x) ((x).w_retcode)
63 # endif
64 #else
65 # define WAIT_T int
66 # ifndef WTERMSIG
67 #  define WTERMSIG(x) ((x) & 0x7f)
68 # endif
69 # ifndef WCOREDUMP
70 #  define WCOREDUMP(x) ((x) & 0x80)
71 # endif
72 # ifndef WEXITSTATUS
73 #  define WEXITSTATUS(x) (((x) >> 8) & 0xff)
74 # endif
75 #endif
76 /* For valid x, exactly one of WIFSIGNALED(x), WIFEXITED(x), WIFSTOPPED(x)
77    is true.  */
78 #ifndef WIFSIGNALED
79 # define WIFSIGNALED(x) (WTERMSIG (x) != 0 && WTERMSIG(x) != 0x7f)
80 #endif
81 #ifndef WIFEXITED
82 # define WIFEXITED(x) (WTERMSIG (x) == 0)
83 #endif
84 #ifndef WIFSTOPPED
85 # define WIFSTOPPED(x) (WTERMSIG (x) == 0x7f)
86 #endif
87 /* Note that portable applications may access
88    WTERMSIG(x) only if WIFSIGNALED(x) is true, and
89    WEXITSTATUS(x) only if WIFEXITED(x) is true.  */
90
91 #endif
92
93 #include "error.h"
94 #include "exit.h"
95 #include "fatal-signal.h"
96 #include "xalloc.h"
97 #include "gettext.h"
98
99 #define _(str) gettext (str)
100
101 #define SIZEOF(a) (sizeof(a) / sizeof(a[0]))
102
103
104 #if defined _MSC_VER || defined __MINGW32__
105
106 /* The return value of spawnvp() is really a process handle as returned
107    by CreateProcess().  Therefore we can kill it using TerminateProcess.  */
108 #define kill(pid,sig) TerminateProcess ((HANDLE) (pid), sig)
109
110 #endif
111
112
113 /* Type of an entry in the slaves array.
114    The 'used' bit determines whether this entry is currently in use.
115    (If pid_t was an atomic type like sig_atomic_t, we could just set the
116    'child' field to 0 when unregistering a slave process, and wouldn't need
117    the 'used' field.)
118    The 'used' and 'child' fields are accessed from within the cleanup_slaves()
119    action, therefore we mark them as 'volatile'.  */
120 typedef struct
121 {
122   volatile sig_atomic_t used;
123   volatile pid_t child;
124 }
125 slaves_entry_t;
126
127 /* The registered slave subprocesses.  */
128 static slaves_entry_t static_slaves[32];
129 static slaves_entry_t * volatile slaves = static_slaves;
130 static sig_atomic_t volatile slaves_count = 0;
131 static size_t slaves_allocated = SIZEOF (static_slaves);
132
133 /* The termination signal for slave subprocesses.
134    2003-10-07:  Terminator becomes Governator.  */
135 #ifdef SIGHUP
136 # define TERMINATOR SIGHUP
137 #else
138 # define TERMINATOR SIGTERM
139 #endif
140
141 /* The cleanup action.  It gets called asynchronously.  */
142 static void
143 cleanup_slaves ()
144 {
145   for (;;)
146     {
147       /* Get the last registered slave.  */
148       size_t n = slaves_count;
149       if (n == 0)
150         break;
151       n--;
152       slaves_count = n;
153       /* Skip unused entries in the slaves array.  */
154       if (slaves[n].used)
155         {
156           pid_t slave = slaves[n].child;
157
158           /* Kill the slave.  */
159           kill (slave, TERMINATOR);
160         }
161     }
162 }
163
164 /* Register a subprocess as being a slave process.  This means that the
165    subprocess will be terminated when its creator receives a catchable fatal
166    signal or exits normally.  Registration ends when wait_subprocess()
167    notices that the subprocess has exited.  */
168 void
169 register_slave_subprocess (pid_t child)
170 {
171   static bool cleanup_slaves_registered = false;
172   if (!cleanup_slaves_registered)
173     {
174       atexit (cleanup_slaves);
175       at_fatal_signal (cleanup_slaves);
176       cleanup_slaves_registered = true;
177     }
178
179   /* Try to store the new slave in an unused entry of the slaves array.  */
180   {
181     slaves_entry_t *s = slaves;
182     slaves_entry_t *s_end = s + slaves_count;
183
184     for (; s < s_end; s++)
185       if (!s->used)
186         {
187           /* The two uses of 'volatile' in the slaves_entry_t type above
188              (and ISO C 99 section 5.1.2.3.(5)) ensure that we mark the
189              entry as used only after the child pid has been written to the
190              memory location s->child.  */
191           s->child = child;
192           s->used = 1;
193           return;
194         }
195   }
196
197   if (slaves_count == slaves_allocated)
198     {
199       /* Extend the slaves array.  Note that we cannot use xrealloc(),
200          because then the cleanup_slaves() function could access an already
201          deallocated array.  */
202       slaves_entry_t *old_slaves = slaves;
203       size_t new_slaves_allocated = 2 * slaves_allocated;
204       slaves_entry_t *new_slaves =
205         malloc (new_slaves_allocated * sizeof (slaves_entry_t));
206       if (new_slaves == NULL)
207         {
208           /* xalloc_die() will call exit() which will invoke cleanup_slaves().
209              Additionally we need to kill child, because it's not yet among
210              the slaves list.  */
211           kill (child, TERMINATOR);
212           xalloc_die ();
213         }
214       memcpy (new_slaves, old_slaves,
215               slaves_allocated * sizeof (slaves_entry_t));
216       slaves = new_slaves;
217       slaves_allocated = new_slaves_allocated;
218       /* Now we can free the old slaves array.  */
219       if (old_slaves != static_slaves)
220         free (old_slaves);
221     }
222   /* The three uses of 'volatile' in the types above (and ISO C 99 section
223      5.1.2.3.(5)) ensure that we increment the slaves_count only after the
224      new slave and its 'used' bit have been written to the memory locations
225      that make up slaves[slaves_count].  */
226   slaves[slaves_count].child = child;
227   slaves[slaves_count].used = 1;
228   slaves_count++;
229 }
230
231 /* Unregister a child from the list of slave subprocesses.  */
232 static inline void
233 unregister_slave_subprocess (pid_t child)
234 {
235   /* The easiest way to remove an entry from a list that can be used by
236      an asynchronous signal handler is just to mark it as unused.  For this,
237      we rely on sig_atomic_t.  */
238   slaves_entry_t *s = slaves;
239   slaves_entry_t *s_end = s + slaves_count;
240
241   for (; s < s_end; s++)
242     if (s->used && s->child == child)
243       s->used = 0;
244 }
245
246
247 /* Wait for a subprocess to finish.  Return its exit code.
248    If it didn't terminate correctly, exit if exit_on_error is true, otherwise
249    return 127.  */
250 int
251 wait_subprocess (pid_t child, const char *progname,
252                  bool null_stderr,
253                  bool slave_process, bool exit_on_error)
254 {
255 #if HAVE_WAITID && defined WNOWAIT
256   /* Use of waitid() with WNOWAIT avoids a race condition: If slave_process is
257      true, and this process sleeps a very long time between the return from
258      waitpid() and the execution of unregister_slave_subprocess(), and
259      meanwhile another process acquires the same PID as child, and then - still
260      before unregister_slave_subprocess() - this process gets a fatal signal,
261      it would kill the other totally unrelated process.  */
262   siginfo_t info;
263   for (;;)
264     {
265       if (waitid (P_PID, child, &info, slave_process ? WNOWAIT : 0) < 0)
266         {
267 # ifdef EINTR
268           if (errno == EINTR)
269             continue;
270 # endif
271           if (exit_on_error || !null_stderr)
272             error (exit_on_error ? EXIT_FAILURE : 0, errno,
273                    _("%s subprocess"), progname);
274           return 127;
275         }
276
277       /* info.si_code is set to one of CLD_EXITED, CLD_KILLED, CLD_DUMPED,
278          CLD_TRAPPED, CLD_STOPPED, CLD_CONTINUED.  Loop until the program
279          terminates.  */
280       if (info.si_code == CLD_EXITED
281           || info.si_code == CLD_KILLED || info.si_code == CLD_DUMPED)
282         break;
283     }
284
285   /* The child process has exited or was signalled.  */
286
287   if (slave_process)
288     {
289       /* Unregister the child from the list of slave subprocesses, so that
290          later, when we exit, we don't kill a totally unrelated process which
291          may have acquired the same pid.  */
292       unregister_slave_subprocess (child);
293
294       /* Now remove the zombie from the process list.  */
295       for (;;)
296         {
297           if (waitid (P_PID, child, &info, 0) < 0)
298             {
299 # ifdef EINTR
300               if (errno == EINTR)
301                 continue;
302 # endif
303               if (exit_on_error || !null_stderr)
304                 error (exit_on_error ? EXIT_FAILURE : 0, errno,
305                        _("%s subprocess"), progname);
306               return 127;
307             }
308           break;
309         }
310     }
311
312   switch (info.si_code)
313     {
314     case CLD_KILLED:
315     case CLD_DUMPED:
316       if (exit_on_error || !null_stderr)
317         error (exit_on_error ? EXIT_FAILURE : 0, 0,
318                _("%s subprocess got fatal signal %d"),
319                progname, info.si_status);
320       return 127;
321     case CLD_EXITED:
322       if (info.si_status == 127)
323         {
324           if (exit_on_error || !null_stderr)
325             error (exit_on_error ? EXIT_FAILURE : 0, 0,
326                    _("%s subprocess failed"), progname);
327           return 127;
328         }
329       return info.si_status;
330     default:
331       abort ();
332     }
333 #else
334   /* waitpid() is just as portable as wait() nowadays.  */
335   WAIT_T status;
336
337   *(int *) &status = 0;
338   for (;;)
339     {
340       int result = waitpid (child, &status, 0);
341
342       if (result != child)
343         {
344 # ifdef EINTR
345           if (errno == EINTR)
346             continue;
347 # endif
348 # if 0 /* defined ECHILD */
349           if (errno == ECHILD)
350             {
351               /* Child process nonexistent?! Assume it terminated
352                  successfully.  */
353               *(int *) &status = 0;
354               break;
355             }
356 # endif
357           if (exit_on_error || !null_stderr)
358             error (exit_on_error ? EXIT_FAILURE : 0, errno,
359                    _("%s subprocess"), progname);
360           return 127;
361         }
362
363       /* One of WIFSIGNALED (status), WIFEXITED (status), WIFSTOPPED (status)
364          must always be true.  Loop until the program terminates.  */
365       if (!WIFSTOPPED (status))
366         break;
367     }
368
369   /* The child process has exited or was signalled.  */
370
371   if (slave_process)
372     /* Unregister the child from the list of slave subprocesses, so that
373        later, when we exit, we don't kill a totally unrelated process which
374        may have acquired the same pid.  */
375     unregister_slave_subprocess (child);
376
377   if (WIFSIGNALED (status))
378     {
379       if (exit_on_error || !null_stderr)
380         error (exit_on_error ? EXIT_FAILURE : 0, 0,
381                _("%s subprocess got fatal signal %d"),
382                progname, (int) WTERMSIG (status));
383       return 127;
384     }
385   if (WEXITSTATUS (status) == 127)
386     {
387       if (exit_on_error || !null_stderr)
388         error (exit_on_error ? EXIT_FAILURE : 0, 0,
389                _("%s subprocess failed"), progname);
390       return 127;
391     }
392   return WEXITSTATUS (status);
393 #endif
394 }