* lib/wait-process.h (wait_subprocess): Accept a new exitsignal argument.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 #define WIN32_LEAN_AND_MEAN
107 #include <windows.h>
108
109 /* The return value of spawnvp() is really a process handle as returned
110    by CreateProcess().  Therefore we can kill it using TerminateProcess.  */
111 #define kill(pid,sig) TerminateProcess ((HANDLE) (pid), sig)
112
113 #endif
114
115
116 /* Type of an entry in the slaves array.
117    The 'used' bit determines whether this entry is currently in use.
118    (If pid_t was an atomic type like sig_atomic_t, we could just set the
119    'child' field to 0 when unregistering a slave process, and wouldn't need
120    the 'used' field.)
121    The 'used' and 'child' fields are accessed from within the cleanup_slaves()
122    action, therefore we mark them as 'volatile'.  */
123 typedef struct
124 {
125   volatile sig_atomic_t used;
126   volatile pid_t child;
127 }
128 slaves_entry_t;
129
130 /* The registered slave subprocesses.  */
131 static slaves_entry_t static_slaves[32];
132 static slaves_entry_t * volatile slaves = static_slaves;
133 static sig_atomic_t volatile slaves_count = 0;
134 static size_t slaves_allocated = SIZEOF (static_slaves);
135
136 /* The termination signal for slave subprocesses.
137    2003-10-07:  Terminator becomes Governator.  */
138 #ifdef SIGHUP
139 # define TERMINATOR SIGHUP
140 #else
141 # define TERMINATOR SIGTERM
142 #endif
143
144 /* The cleanup action.  It gets called asynchronously.  */
145 static void
146 cleanup_slaves (void)
147 {
148   for (;;)
149     {
150       /* Get the last registered slave.  */
151       size_t n = slaves_count;
152       if (n == 0)
153         break;
154       n--;
155       slaves_count = n;
156       /* Skip unused entries in the slaves array.  */
157       if (slaves[n].used)
158         {
159           pid_t slave = slaves[n].child;
160
161           /* Kill the slave.  */
162           kill (slave, TERMINATOR);
163         }
164     }
165 }
166
167 /* Register a subprocess as being a slave process.  This means that the
168    subprocess will be terminated when its creator receives a catchable fatal
169    signal or exits normally.  Registration ends when wait_subprocess()
170    notices that the subprocess has exited.  */
171 void
172 register_slave_subprocess (pid_t child)
173 {
174   static bool cleanup_slaves_registered = false;
175   if (!cleanup_slaves_registered)
176     {
177       atexit (cleanup_slaves);
178       at_fatal_signal (cleanup_slaves);
179       cleanup_slaves_registered = true;
180     }
181
182   /* Try to store the new slave in an unused entry of the slaves array.  */
183   {
184     slaves_entry_t *s = slaves;
185     slaves_entry_t *s_end = s + slaves_count;
186
187     for (; s < s_end; s++)
188       if (!s->used)
189         {
190           /* The two uses of 'volatile' in the slaves_entry_t type above
191              (and ISO C 99 section 5.1.2.3.(5)) ensure that we mark the
192              entry as used only after the child pid has been written to the
193              memory location s->child.  */
194           s->child = child;
195           s->used = 1;
196           return;
197         }
198   }
199
200   if (slaves_count == slaves_allocated)
201     {
202       /* Extend the slaves array.  Note that we cannot use xrealloc(),
203          because then the cleanup_slaves() function could access an already
204          deallocated array.  */
205       slaves_entry_t *old_slaves = slaves;
206       size_t new_slaves_allocated = 2 * slaves_allocated;
207       slaves_entry_t *new_slaves =
208         malloc (new_slaves_allocated * sizeof (slaves_entry_t));
209       if (new_slaves == NULL)
210         {
211           /* xalloc_die() will call exit() which will invoke cleanup_slaves().
212              Additionally we need to kill child, because it's not yet among
213              the slaves list.  */
214           kill (child, TERMINATOR);
215           xalloc_die ();
216         }
217       memcpy (new_slaves, old_slaves,
218               slaves_allocated * sizeof (slaves_entry_t));
219       slaves = new_slaves;
220       slaves_allocated = new_slaves_allocated;
221       /* Now we can free the old slaves array.  */
222       if (old_slaves != static_slaves)
223         free (old_slaves);
224     }
225   /* The three uses of 'volatile' in the types above (and ISO C 99 section
226      5.1.2.3.(5)) ensure that we increment the slaves_count only after the
227      new slave and its 'used' bit have been written to the memory locations
228      that make up slaves[slaves_count].  */
229   slaves[slaves_count].child = child;
230   slaves[slaves_count].used = 1;
231   slaves_count++;
232 }
233
234 /* Unregister a child from the list of slave subprocesses.  */
235 static inline void
236 unregister_slave_subprocess (pid_t child)
237 {
238   /* The easiest way to remove an entry from a list that can be used by
239      an asynchronous signal handler is just to mark it as unused.  For this,
240      we rely on sig_atomic_t.  */
241   slaves_entry_t *s = slaves;
242   slaves_entry_t *s_end = s + slaves_count;
243
244   for (; s < s_end; s++)
245     if (s->used && s->child == child)
246       s->used = 0;
247 }
248
249
250 /* Wait for a subprocess to finish.  Return its exit code.
251    If it didn't terminate correctly, exit if exit_on_error is true, otherwise
252    return 127.  */
253 int
254 wait_subprocess (pid_t child, const char *progname, int *exitsignal,
255                  bool ignore_sigpipe, bool null_stderr,
256                  bool slave_process, bool exit_on_error)
257 {
258 #if HAVE_WAITID && defined WNOWAIT && 0
259   /* Commented out because waitid() with WNOWAIT doesn't work: On Solaris 7
260      and OSF/1 4.0, it returns -1 and sets errno = ECHILD, and on HP-UX 10.20
261      it just hangs.  */
262   /* Use of waitid() with WNOWAIT avoids a race condition: If slave_process is
263      true, and this process sleeps a very long time between the return from
264      waitpid() and the execution of unregister_slave_subprocess(), and
265      meanwhile another process acquires the same PID as child, and then - still
266      before unregister_slave_subprocess() - this process gets a fatal signal,
267      it would kill the other totally unrelated process.  */
268   siginfo_t info;
269   for (;;)
270     {
271       if (waitid (P_PID, child, &info, slave_process ? WNOWAIT : 0) < 0)
272         {
273 # ifdef EINTR
274           if (errno == EINTR)
275             continue;
276 # endif
277           if (exit_on_error || !null_stderr)
278             error (exit_on_error ? EXIT_FAILURE : 0, errno,
279                    _("%s subprocess"), progname);
280           return 127;
281         }
282
283       /* info.si_code is set to one of CLD_EXITED, CLD_KILLED, CLD_DUMPED,
284          CLD_TRAPPED, CLD_STOPPED, CLD_CONTINUED.  Loop until the program
285          terminates.  */
286       if (info.si_code == CLD_EXITED
287           || info.si_code == CLD_KILLED || info.si_code == CLD_DUMPED)
288         break;
289     }
290
291   /* The child process has exited or was signalled.  */
292
293   if (slave_process)
294     {
295       /* Unregister the child from the list of slave subprocesses, so that
296          later, when we exit, we don't kill a totally unrelated process which
297          may have acquired the same pid.  */
298       unregister_slave_subprocess (child);
299
300       /* Now remove the zombie from the process list.  */
301       for (;;)
302         {
303           if (waitid (P_PID, child, &info, 0) < 0)
304             {
305 # ifdef EINTR
306               if (errno == EINTR)
307                 continue;
308 # endif
309               if (exit_on_error || !null_stderr)
310                 error (exit_on_error ? EXIT_FAILURE : 0, errno,
311                        _("%s subprocess"), progname);
312               return 127;
313             }
314           break;
315         }
316     }
317
318   switch (info.si_code)
319     {
320     case CLD_KILLED:
321     case CLD_DUMPED:
322 # ifdef SIGPIPE
323       if (info.si_status == SIGPIPE && ignore_sigpipe)
324         return 0;
325 # endif
326       if (exit_on_error || !null_stderr)
327         error (exit_on_error ? EXIT_FAILURE : 0, 0,
328                _("%s subprocess got fatal signal %d"),
329                progname, info.si_status);
330       return 127;
331     case CLD_EXITED:
332       if (info.si_status == 127)
333         {
334           if (exit_on_error || !null_stderr)
335             error (exit_on_error ? EXIT_FAILURE : 0, 0,
336                    _("%s subprocess failed"), progname);
337           return 127;
338         }
339       return info.si_status;
340     default:
341       abort ();
342     }
343 #else
344   /* waitpid() is just as portable as wait() nowadays.  */
345   WAIT_T status;
346
347   *(int *) &status = 0;
348   if (exitsignal) *exitsignal = 0;
349   for (;;)
350     {
351       int result = waitpid (child, &status, 0);
352
353       if (result != child)
354         {
355 # ifdef EINTR
356           if (errno == EINTR)
357             continue;
358 # endif
359 # if 0 /* defined ECHILD */
360           if (errno == ECHILD)
361             {
362               /* Child process nonexistent?! Assume it terminated
363                  successfully.  */
364               *(int *) &status = 0;
365               break;
366             }
367 # endif
368           if (exit_on_error || !null_stderr)
369             error (exit_on_error ? EXIT_FAILURE : 0, errno,
370                    _("%s subprocess"), progname);
371           return 127;
372         }
373
374       /* One of WIFSIGNALED (status), WIFEXITED (status), WIFSTOPPED (status)
375          must always be true.  Loop until the program terminates.  */
376       if (!WIFSTOPPED (status))
377         break;
378     }
379
380   /* The child process has exited or was signalled.  */
381
382   if (slave_process)
383     /* Unregister the child from the list of slave subprocesses, so that
384        later, when we exit, we don't kill a totally unrelated process which
385        may have acquired the same pid.  */
386     unregister_slave_subprocess (child);
387
388   if (WIFSIGNALED (status))
389     {
390 # ifdef SIGPIPE
391       if (WTERMSIG (status) == SIGPIPE && ignore_sigpipe)
392         return 0;
393 # endif
394       if (exit_on_error || !null_stderr)
395         error (exit_on_error ? EXIT_FAILURE : 0, 0,
396                _("%s subprocess got fatal signal %d"),
397                progname, (int) WTERMSIG (status));
398       if (exitsignal) *exitsignal = WTERMSIG (status);
399       return 127;
400     }
401   if (WEXITSTATUS (status) == 127)
402     {
403       if (exit_on_error || !null_stderr)
404         error (exit_on_error ? EXIT_FAILURE : 0, 0,
405                _("%s subprocess failed"), progname);
406       return 127;
407     }
408   return WEXITSTATUS (status);
409 #endif
410 }