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