47f408520450e652c72e700147bd54d30f484ec1
[gnulib.git] / lib / execute.c
1 /* Creation of autonomous subprocesses.
2    Copyright (C) 2001-2004, 2006-2008 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 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 #include <config.h>
20
21 /* Specification.  */
22 #include "execute.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdbool.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <unistd.h>
30
31 #include "error.h"
32 #include "fatal-signal.h"
33 #include "wait-process.h"
34 #include "gettext.h"
35
36 #define _(str) gettext (str)
37
38 #if defined _MSC_VER || defined __MINGW32__
39
40 /* Native Woe32 API.  */
41 # include <process.h>
42 # include "w32spawn.h"
43
44 #else
45
46 /* Unix API.  */
47 # if HAVE_POSIX_SPAWN
48 #  include <spawn.h>
49 # else
50 #  if HAVE_VFORK_H
51 #   include <vfork.h>
52 #  endif
53 # endif
54
55 #endif
56
57 #ifndef STDIN_FILENO
58 # define STDIN_FILENO 0
59 #endif
60 #ifndef STDOUT_FILENO
61 # define STDOUT_FILENO 1
62 #endif
63 #ifndef STDERR_FILENO
64 # define STDERR_FILENO 2
65 #endif
66
67 /* The results of open() in this file are not used with fchdir,
68    therefore save some unnecessary work in fchdir.c.  */
69 #undef open
70 #undef close
71
72
73 #ifdef EINTR
74
75 /* EINTR handling for close(), open().
76    These functions can return -1/EINTR even though we don't have any
77    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
78
79 static inline int
80 nonintr_close (int fd)
81 {
82   int retval;
83
84   do
85     retval = close (fd);
86   while (retval < 0 && errno == EINTR);
87
88   return retval;
89 }
90 #define close nonintr_close
91
92 static inline int
93 nonintr_open (const char *pathname, int oflag, mode_t mode)
94 {
95   int retval;
96
97   do
98     retval = open (pathname, oflag, mode);
99   while (retval < 0 && errno == EINTR);
100
101   return retval;
102 }
103 #undef open /* avoid warning on VMS */
104 #define open nonintr_open
105
106 #endif
107
108
109 /* Execute a command, optionally redirecting any of the three standard file
110    descriptors to /dev/null.  Return its exit code.
111    If it didn't terminate correctly, exit if exit_on_error is true, otherwise
112    return 127.
113    If slave_process is true, the child process will be terminated when its
114    creator receives a catchable fatal signal.  */
115 int
116 execute (const char *progname,
117          const char *prog_path, char **prog_argv,
118          bool ignore_sigpipe,
119          bool null_stdin, bool null_stdout, bool null_stderr,
120          bool slave_process, bool exit_on_error,
121          int *termsigp)
122 {
123 #if defined _MSC_VER || defined __MINGW32__
124
125   /* Native Woe32 API.  */
126   int orig_stdin;
127   int orig_stdout;
128   int orig_stderr;
129   int exitcode;
130   int nullinfd;
131   int nulloutfd;
132
133   /* FIXME: Need to free memory allocated by prepare_spawn.  */
134   prog_argv = prepare_spawn (prog_argv);
135
136   /* Save standard file handles of parent process.  */
137   if (null_stdin)
138     orig_stdin = dup_noinherit (STDIN_FILENO);
139   if (null_stdout)
140     orig_stdout = dup_noinherit (STDOUT_FILENO);
141   if (null_stderr)
142     orig_stderr = dup_noinherit (STDERR_FILENO);
143   exitcode = -1;
144
145   /* Create standard file handles of child process.  */
146   nullinfd = -1;
147   nulloutfd = -1;
148   if ((!null_stdin
149        || ((nullinfd = open ("NUL", O_RDONLY, 0)) >= 0
150            && (nullinfd == STDIN_FILENO
151                || (dup2 (nullinfd, STDIN_FILENO) >= 0
152                    && close (nullinfd) >= 0))))
153       && (!(null_stdout || null_stderr)
154           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
155               && (!null_stdout
156                   || nulloutfd == STDOUT_FILENO
157                   || dup2 (nulloutfd, STDOUT_FILENO) >= 0)
158               && (!null_stderr
159                   || nulloutfd == STDERR_FILENO
160                   || dup2 (nulloutfd, STDERR_FILENO) >= 0)
161               && ((null_stdout && nulloutfd == STDOUT_FILENO)
162                   || (null_stderr && nulloutfd == STDERR_FILENO)
163                   || close (nulloutfd) >= 0))))
164     {
165       exitcode = spawnvp (P_WAIT, prog_path, prog_argv);
166       if (exitcode < 0 && errno == ENOEXEC)
167         {
168           /* prog is not an native executable.  Try to execute it as a
169              shell script.  Note that prepare_spawn() has already prepended
170              a hidden element "sh.exe" to prog_argv.  */
171           --prog_argv;
172           exitcode = spawnvp (P_WAIT, prog_argv[0], prog_argv);
173         }
174     }
175   if (nulloutfd >= 0)
176     close (nulloutfd);
177   if (nullinfd >= 0)
178     close (nullinfd);
179
180   /* Restore standard file handles of parent process.  */
181   if (null_stderr)
182     dup2 (orig_stderr, STDERR_FILENO), close (orig_stderr);
183   if (null_stdout)
184     dup2 (orig_stdout, STDOUT_FILENO), close (orig_stdout);
185   if (null_stdin)
186     dup2 (orig_stdin, STDIN_FILENO), close (orig_stdin);
187
188   if (termsigp != NULL)
189     *termsigp = 0;
190
191   if (exitcode == -1)
192     {
193       if (exit_on_error || !null_stderr)
194         error (exit_on_error ? EXIT_FAILURE : 0, errno,
195                _("%s subprocess failed"), progname);
196       return 127;
197     }
198
199   return exitcode;
200
201 #else
202
203   /* Unix API.  */
204   /* Note about 127: Some errors during posix_spawnp() cause the function
205      posix_spawnp() to return an error code; some other errors cause the
206      subprocess to exit with return code 127.  It is implementation
207      dependent which error is reported which way.  We treat both cases as
208      equivalent.  */
209 #if HAVE_POSIX_SPAWN
210   sigset_t blocked_signals;
211   posix_spawn_file_actions_t actions;
212   bool actions_allocated;
213   posix_spawnattr_t attrs;
214   bool attrs_allocated;
215   int err;
216   pid_t child;
217 #else
218   int child;
219 #endif
220
221 #if HAVE_POSIX_SPAWN
222   if (slave_process)
223     {
224       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
225       block_fatal_signals ();
226     }
227   actions_allocated = false;
228   attrs_allocated = false;
229   if ((err = posix_spawn_file_actions_init (&actions)) != 0
230       || (actions_allocated = true,
231           (null_stdin
232             && (err = posix_spawn_file_actions_addopen (&actions,
233                                                         STDIN_FILENO,
234                                                         "/dev/null", O_RDONLY,
235                                                         0))
236                != 0)
237           || (null_stdout
238               && (err = posix_spawn_file_actions_addopen (&actions,
239                                                           STDOUT_FILENO,
240                                                           "/dev/null", O_RDWR,
241                                                           0))
242                  != 0)
243           || (null_stderr
244               && (err = posix_spawn_file_actions_addopen (&actions,
245                                                           STDERR_FILENO,
246                                                           "/dev/null", O_RDWR,
247                                                           0))
248                  != 0)
249           || (slave_process
250               && ((err = posix_spawnattr_init (&attrs)) != 0
251                   || (attrs_allocated = true,
252                       (err = posix_spawnattr_setsigmask (&attrs,
253                                                          &blocked_signals))
254                       != 0
255                       || (err = posix_spawnattr_setflags (&attrs,
256                                                         POSIX_SPAWN_SETSIGMASK))
257                          != 0)))
258           || (err = posix_spawnp (&child, prog_path, &actions,
259                                   attrs_allocated ? &attrs : NULL, prog_argv,
260                                   environ))
261              != 0))
262     {
263       if (actions_allocated)
264         posix_spawn_file_actions_destroy (&actions);
265       if (attrs_allocated)
266         posix_spawnattr_destroy (&attrs);
267       if (slave_process)
268         unblock_fatal_signals ();
269       if (termsigp != NULL)
270         *termsigp = 0;
271       if (exit_on_error || !null_stderr)
272         error (exit_on_error ? EXIT_FAILURE : 0, err,
273                _("%s subprocess failed"), progname);
274       return 127;
275     }
276   posix_spawn_file_actions_destroy (&actions);
277   if (attrs_allocated)
278     posix_spawnattr_destroy (&attrs);
279 #else
280   if (slave_process)
281     block_fatal_signals ();
282   /* Use vfork() instead of fork() for efficiency.  */
283   if ((child = vfork ()) == 0)
284     {
285       /* Child process code.  */
286       int nullinfd;
287       int nulloutfd;
288
289       if ((!null_stdin
290            || ((nullinfd = open ("/dev/null", O_RDONLY, 0)) >= 0
291                && (nullinfd == STDIN_FILENO
292                    || (dup2 (nullinfd, STDIN_FILENO) >= 0
293                        && close (nullinfd) >= 0))))
294           && (!(null_stdout || null_stderr)
295               || ((nulloutfd = open ("/dev/null", O_RDWR, 0)) >= 0
296                   && (!null_stdout
297                       || nulloutfd == STDOUT_FILENO
298                       || dup2 (nulloutfd, STDOUT_FILENO) >= 0)
299                   && (!null_stderr
300                       || nulloutfd == STDERR_FILENO
301                       || dup2 (nulloutfd, STDERR_FILENO) >= 0)
302                   && ((null_stdout && nulloutfd == STDOUT_FILENO)
303                       || (null_stderr && nulloutfd == STDERR_FILENO)
304                       || close (nulloutfd) >= 0)))
305           && (!slave_process || (unblock_fatal_signals (), true)))
306         execvp (prog_path, prog_argv);
307       _exit (127);
308     }
309   if (child == -1)
310     {
311       if (slave_process)
312         unblock_fatal_signals ();
313       if (termsigp != NULL)
314         *termsigp = 0;
315       if (exit_on_error || !null_stderr)
316         error (exit_on_error ? EXIT_FAILURE : 0, errno,
317                _("%s subprocess failed"), progname);
318       return 127;
319     }
320 #endif
321   if (slave_process)
322     {
323       register_slave_subprocess (child);
324       unblock_fatal_signals ();
325     }
326
327   return wait_subprocess (child, progname, ignore_sigpipe, null_stderr,
328                           slave_process, exit_on_error, termsigp);
329
330 #endif
331 }