d842c77f9c31bc71d6b4fbdfc1cb5abd93aa9121
[gnulib.git] / lib / pipe.c
1 /* Creation of subprocesses, communicating via pipes.
2    Copyright (C) 2001-2004, 2006-2009 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 "pipe.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <unistd.h>
29
30 #include "error.h"
31 #include "fatal-signal.h"
32 #include "unistd-safer.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 /* The results of open() in this file are not used with fchdir,
58    therefore save some unnecessary work in fchdir.c.  */
59 #undef open
60 #undef close
61
62
63 #ifdef EINTR
64
65 /* EINTR handling for close().
66    These functions can return -1/EINTR even though we don't have any
67    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
68
69 static inline int
70 nonintr_close (int fd)
71 {
72   int retval;
73
74   do
75     retval = close (fd);
76   while (retval < 0 && errno == EINTR);
77
78   return retval;
79 }
80 #define close nonintr_close
81
82 static inline int
83 nonintr_open (const char *pathname, int oflag, mode_t mode)
84 {
85   int retval;
86
87   do
88     retval = open (pathname, oflag, mode);
89   while (retval < 0 && errno == EINTR);
90
91   return retval;
92 }
93 #undef open /* avoid warning on VMS */
94 #define open nonintr_open
95
96 #endif
97
98
99 /* Open a pipe connected to a child process.
100  *
101  *           write       system                read
102  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child       if pipe_stdin
103  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child       if pipe_stdout
104  *           read        system                write
105  *
106  * At least one of pipe_stdin, pipe_stdout must be true.
107  * pipe_stdin and prog_stdin together determine the child's standard input.
108  * pipe_stdout and prog_stdout together determine the child's standard output.
109  * If pipe_stdin is true, prog_stdin is ignored.
110  * If pipe_stdout is true, prog_stdout is ignored.
111  */
112 static pid_t
113 create_pipe (const char *progname,
114              const char *prog_path, char **prog_argv,
115              bool pipe_stdin, bool pipe_stdout,
116              const char *prog_stdin, const char *prog_stdout,
117              bool null_stderr,
118              bool slave_process, bool exit_on_error,
119              int fd[2])
120 {
121 #if defined _MSC_VER || defined __MINGW32__
122
123   /* Native Woe32 API.
124      This uses _pipe(), dup2(), and spawnv().  It could also be implemented
125      using the low-level functions CreatePipe(), DuplicateHandle(),
126      CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
127      and cvs source code.  */
128   int ifd[2];
129   int ofd[2];
130   int orig_stdin;
131   int orig_stdout;
132   int orig_stderr;
133   int child;
134   int nulloutfd;
135   int stdinfd;
136   int stdoutfd;
137
138   /* FIXME: Need to free memory allocated by prepare_spawn.  */
139   prog_argv = prepare_spawn (prog_argv);
140
141   if (pipe_stdout)
142     if (_pipe (ifd, 4096, O_BINARY | O_NOINHERIT) < 0
143         || (ifd[0] = fd_safer (ifd[0])) < 0)
144       error (EXIT_FAILURE, errno, _("cannot create pipe"));
145   if (pipe_stdin)
146     if (_pipe (ofd, 4096, O_BINARY | O_NOINHERIT) < 0
147         || (ofd[1] = fd_safer (ofd[1])) < 0)
148       error (EXIT_FAILURE, errno, _("cannot create pipe"));
149 /* Data flow diagram:
150  *
151  *           write        system         read
152  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
153  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
154  *           read         system         write
155  *
156  */
157
158   /* Save standard file handles of parent process.  */
159   if (pipe_stdin || prog_stdin != NULL)
160     orig_stdin = dup_noinherit (STDIN_FILENO);
161   if (pipe_stdout || prog_stdout != NULL)
162     orig_stdout = dup_noinherit (STDOUT_FILENO);
163   if (null_stderr)
164     orig_stderr = dup_noinherit (STDERR_FILENO);
165   child = -1;
166
167   /* Create standard file handles of child process.  */
168   nulloutfd = -1;
169   stdinfd = -1;
170   stdoutfd = -1;
171   if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
172       && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
173       && (!null_stderr
174           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
175               && (nulloutfd == STDERR_FILENO
176                   || (dup2 (nulloutfd, STDERR_FILENO) >= 0
177                       && close (nulloutfd) >= 0))))
178       && (pipe_stdin
179           || prog_stdin == NULL
180           || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
181               && (stdinfd == STDIN_FILENO
182                   || (dup2 (stdinfd, STDIN_FILENO) >= 0
183                       && close (stdinfd) >= 0))))
184       && (pipe_stdout
185           || prog_stdout == NULL
186           || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
187               && (stdoutfd == STDOUT_FILENO
188                   || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
189                       && close (stdoutfd) >= 0)))))
190     /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
191        but it inherits all open()ed or dup2()ed file handles (which is what
192        we want in the case of STD*_FILENO) and also orig_stdin,
193        orig_stdout, orig_stderr (which is not explicitly wanted but
194        harmless).  */
195     /* Use spawnvpe and pass the environment explicitly.  This is needed if
196        the program has modified the environment using putenv() or [un]setenv().
197        On Windows, programs have two environments, one in the "environment
198        block" of the process and managed through SetEnvironmentVariable(), and
199        one inside the process, in the location retrieved by the 'environ'
200        macro.  When using spawnvp() without 'e', the child process inherits a
201        copy of the environment block - ignoring the effects of putenv() and
202        [un]setenv().  */
203     {
204       child = spawnvpe (P_NOWAIT, prog_path, prog_argv, environ);
205       if (child < 0 && errno == ENOEXEC)
206         {
207           /* prog is not an native executable.  Try to execute it as a
208              shell script.  Note that prepare_spawn() has already prepended
209              a hidden element "sh.exe" to prog_argv.  */
210           --prog_argv;
211           child = spawnvpe (P_NOWAIT, prog_argv[0], prog_argv, environ);
212         }
213     }
214   if (stdinfd >= 0)
215     close (stdinfd);
216   if (stdoutfd >= 0)
217     close (stdoutfd);
218   if (nulloutfd >= 0)
219     close (nulloutfd);
220
221   /* Restore standard file handles of parent process.  */
222   if (null_stderr)
223     dup2 (orig_stderr, STDERR_FILENO), close (orig_stderr);
224   if (pipe_stdout || prog_stdout != NULL)
225     dup2 (orig_stdout, STDOUT_FILENO), close (orig_stdout);
226   if (pipe_stdin || prog_stdin != NULL)
227     dup2 (orig_stdin, STDIN_FILENO), close (orig_stdin);
228
229   if (pipe_stdin)
230     close (ofd[0]);
231   if (pipe_stdout)
232     close (ifd[1]);
233   if (child == -1)
234     {
235       if (exit_on_error || !null_stderr)
236         error (exit_on_error ? EXIT_FAILURE : 0, errno,
237                _("%s subprocess failed"), progname);
238       if (pipe_stdout)
239         close (ifd[0]);
240       if (pipe_stdin)
241         close (ofd[1]);
242       return -1;
243     }
244
245   if (pipe_stdout)
246     fd[0] = ifd[0];
247   if (pipe_stdin)
248     fd[1] = ofd[1];
249   return child;
250
251 #else
252
253   /* Unix API.  */
254   int ifd[2];
255   int ofd[2];
256 # if HAVE_POSIX_SPAWN
257   sigset_t blocked_signals;
258   posix_spawn_file_actions_t actions;
259   bool actions_allocated;
260   posix_spawnattr_t attrs;
261   bool attrs_allocated;
262   int err;
263   pid_t child;
264 # else
265   int child;
266 # endif
267
268   if (pipe_stdout)
269     if (pipe (ifd) < 0
270         || (ifd[0] = fd_safer (ifd[0])) < 0)
271       error (EXIT_FAILURE, errno, _("cannot create pipe"));
272   if (pipe_stdin)
273     if (pipe (ofd) < 0
274         || (ofd[1] = fd_safer (ofd[1])) < 0)
275       error (EXIT_FAILURE, errno, _("cannot create pipe"));
276 /* Data flow diagram:
277  *
278  *           write        system         read
279  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
280  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
281  *           read         system         write
282  *
283  */
284
285 # if HAVE_POSIX_SPAWN
286   if (slave_process)
287     {
288       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
289       block_fatal_signals ();
290     }
291   actions_allocated = false;
292   attrs_allocated = false;
293   if ((err = posix_spawn_file_actions_init (&actions)) != 0
294       || (actions_allocated = true,
295           (pipe_stdin
296            && (err = posix_spawn_file_actions_adddup2 (&actions,
297                                                        ofd[0], STDIN_FILENO))
298               != 0)
299           || (pipe_stdout
300               && (err = posix_spawn_file_actions_adddup2 (&actions,
301                                                           ifd[1], STDOUT_FILENO))
302                  != 0)
303           || (pipe_stdin
304               && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
305                  != 0)
306           || (pipe_stdout
307               && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
308                  != 0)
309           || (pipe_stdin
310               && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
311                  != 0)
312           || (pipe_stdout
313               && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
314                  != 0)
315           || (null_stderr
316               && (err = posix_spawn_file_actions_addopen (&actions,
317                                                           STDERR_FILENO,
318                                                           "/dev/null", O_RDWR,
319                                                           0))
320                  != 0)
321           || (!pipe_stdin
322               && prog_stdin != NULL
323               && (err = posix_spawn_file_actions_addopen (&actions,
324                                                           STDIN_FILENO,
325                                                           prog_stdin, O_RDONLY,
326                                                           0))
327                  != 0)
328           || (!pipe_stdout
329               && prog_stdout != NULL
330               && (err = posix_spawn_file_actions_addopen (&actions,
331                                                           STDOUT_FILENO,
332                                                           prog_stdout, O_WRONLY,
333                                                           0))
334                  != 0)
335           || (slave_process
336               && ((err = posix_spawnattr_init (&attrs)) != 0
337                   || (attrs_allocated = true,
338                       (err = posix_spawnattr_setsigmask (&attrs,
339                                                          &blocked_signals))
340                       != 0
341                       || (err = posix_spawnattr_setflags (&attrs,
342                                                         POSIX_SPAWN_SETSIGMASK))
343                          != 0)))
344           || (err = posix_spawnp (&child, prog_path, &actions,
345                                   attrs_allocated ? &attrs : NULL, prog_argv,
346                                   environ))
347              != 0))
348     {
349       if (actions_allocated)
350         posix_spawn_file_actions_destroy (&actions);
351       if (attrs_allocated)
352         posix_spawnattr_destroy (&attrs);
353       if (slave_process)
354         unblock_fatal_signals ();
355       if (exit_on_error || !null_stderr)
356         error (exit_on_error ? EXIT_FAILURE : 0, err,
357                _("%s subprocess failed"), progname);
358       if (pipe_stdout)
359         {
360           close (ifd[0]);
361           close (ifd[1]);
362         }
363       if (pipe_stdin)
364         {
365           close (ofd[0]);
366           close (ofd[1]);
367         }
368       return -1;
369     }
370   posix_spawn_file_actions_destroy (&actions);
371   if (attrs_allocated)
372     posix_spawnattr_destroy (&attrs);
373 # else
374   if (slave_process)
375     block_fatal_signals ();
376   /* Use vfork() instead of fork() for efficiency.  */
377   if ((child = vfork ()) == 0)
378     {
379       /* Child process code.  */
380       int nulloutfd;
381       int stdinfd;
382       int stdoutfd;
383
384       if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
385           && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
386           && (!pipe_stdin || close (ofd[0]) >= 0)
387           && (!pipe_stdout || close (ifd[1]) >= 0)
388           && (!pipe_stdin || close (ofd[1]) >= 0)
389           && (!pipe_stdout || close (ifd[0]) >= 0)
390           && (!null_stderr
391               || ((nulloutfd = open ("/dev/null", O_RDWR, 0)) >= 0
392                   && (nulloutfd == STDERR_FILENO
393                       || (dup2 (nulloutfd, STDERR_FILENO) >= 0
394                           && close (nulloutfd) >= 0))))
395           && (pipe_stdin
396               || prog_stdin == NULL
397               || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
398                   && (stdinfd == STDIN_FILENO
399                       || (dup2 (stdinfd, STDIN_FILENO) >= 0
400                           && close (stdinfd) >= 0))))
401           && (pipe_stdout
402               || prog_stdout == NULL
403               || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
404                   && (stdoutfd == STDOUT_FILENO
405                       || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
406                           && close (stdoutfd) >= 0))))
407           && (!slave_process || (unblock_fatal_signals (), true)))
408         execvp (prog_path, prog_argv);
409       _exit (127);
410     }
411   if (child == -1)
412     {
413       if (slave_process)
414         unblock_fatal_signals ();
415       if (exit_on_error || !null_stderr)
416         error (exit_on_error ? EXIT_FAILURE : 0, errno,
417                _("%s subprocess failed"), progname);
418       if (pipe_stdout)
419         {
420           close (ifd[0]);
421           close (ifd[1]);
422         }
423       if (pipe_stdin)
424         {
425           close (ofd[0]);
426           close (ofd[1]);
427         }
428       return -1;
429     }
430 # endif
431   if (slave_process)
432     {
433       register_slave_subprocess (child);
434       unblock_fatal_signals ();
435     }
436   if (pipe_stdin)
437     close (ofd[0]);
438   if (pipe_stdout)
439     close (ifd[1]);
440
441   if (pipe_stdout)
442     fd[0] = ifd[0];
443   if (pipe_stdin)
444     fd[1] = ofd[1];
445   return child;
446
447 #endif
448 }
449
450 /* Open a bidirectional pipe.
451  *
452  *           write       system                read
453  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child
454  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
455  *           read        system                write
456  *
457  */
458 pid_t
459 create_pipe_bidi (const char *progname,
460                   const char *prog_path, char **prog_argv,
461                   bool null_stderr,
462                   bool slave_process, bool exit_on_error,
463                   int fd[2])
464 {
465   pid_t result = create_pipe (progname, prog_path, prog_argv,
466                               true, true, NULL, NULL,
467                               null_stderr, slave_process, exit_on_error,
468                               fd);
469   return result;
470 }
471
472 /* Open a pipe for input from a child process.
473  * The child's stdin comes from a file.
474  *
475  *           read        system                write
476  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
477  *
478  */
479 pid_t
480 create_pipe_in (const char *progname,
481                 const char *prog_path, char **prog_argv,
482                 const char *prog_stdin, bool null_stderr,
483                 bool slave_process, bool exit_on_error,
484                 int fd[1])
485 {
486   int iofd[2];
487   pid_t result = create_pipe (progname, prog_path, prog_argv,
488                               false, true, prog_stdin, NULL,
489                               null_stderr, slave_process, exit_on_error,
490                               iofd);
491   if (result != -1)
492     fd[0] = iofd[0];
493   return result;
494 }
495
496 /* Open a pipe for output to a child process.
497  * The child's stdout goes to a file.
498  *
499  *           write       system                read
500  *    parent  ->   fd[0]   ->   STDIN_FILENO    ->   child
501  *
502  */
503 pid_t
504 create_pipe_out (const char *progname,
505                  const char *prog_path, char **prog_argv,
506                  const char *prog_stdout, bool null_stderr,
507                  bool slave_process, bool exit_on_error,
508                  int fd[1])
509 {
510   int iofd[2];
511   pid_t result = create_pipe (progname, prog_path, prog_argv,
512                               true, false, NULL, prog_stdout,
513                               null_stderr, slave_process, exit_on_error,
514                               iofd);
515   if (result != -1)
516     fd[0] = iofd[1];
517   return result;
518 }