gspawn: support creating pipes with O_CLOEXEC
[platform/upstream/glib.git] / glib / gspawn.c
1 /* gspawn.c - Process launching
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *  g_execvpe implementation based on GNU libc execvp:
5  *   Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
6  *
7  * GLib is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2 of the
10  * License, or (at your option) any later version.
11  *
12  * GLib is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with GLib; see the file COPYING.LIB.  If not, write
19  * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include "config.h"
24
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <stdlib.h>   /* for fdwalk */
34 #include <dirent.h>
35
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
39
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
43
44 #include "gspawn.h"
45 #include "gthread.h"
46
47 #include "genviron.h"
48 #include "gmem.h"
49 #include "gmain.h"
50 #include "gshell.h"
51 #include "gstring.h"
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
54 #include "gutils.h"
55 #include "glibintl.h"
56 #include "glib-unix.h"
57
58 /**
59  * SECTION:spawn
60  * @Short_description: process launching
61  * @Title: Spawning Processes
62  */
63
64
65
66 static gint g_execute (const gchar  *file,
67                        gchar **argv,
68                        gchar **envp,
69                        gboolean search_path,
70                        gboolean search_path_from_envp);
71
72 static gboolean fork_exec_with_pipes (gboolean              intermediate_child,
73                                       const gchar          *working_directory,
74                                       gchar               **argv,
75                                       gchar               **envp,
76                                       gboolean              close_descriptors,
77                                       gboolean              search_path,
78                                       gboolean              search_path_from_envp,
79                                       gboolean              stdout_to_null,
80                                       gboolean              stderr_to_null,
81                                       gboolean              child_inherits_stdin,
82                                       gboolean              file_and_argv_zero,
83                                       gboolean              cloexec_pipes,
84                                       GSpawnChildSetupFunc  child_setup,
85                                       gpointer              user_data,
86                                       GPid                 *child_pid,
87                                       gint                 *standard_input,
88                                       gint                 *standard_output,
89                                       gint                 *standard_error,
90                                       GError              **error);
91
92 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
93 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
94
95 /**
96  * g_spawn_async:
97  * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
98  * @argv: (array zero-terminated=1): child's argument vector
99  * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
100  * @flags: flags from #GSpawnFlags
101  * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
102  * @user_data: (closure): user data for @child_setup
103  * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
104  * @error: return location for error
105  * 
106  * See g_spawn_async_with_pipes() for a full description; this function
107  * simply calls the g_spawn_async_with_pipes() without any pipes.
108  *
109  * You should call g_spawn_close_pid() on the returned child process
110  * reference when you don't need it any more.
111  * 
112  * <note><para>
113  * If you are writing a GTK+ application, and the program you 
114  * are spawning is a graphical application, too, then you may
115  * want to use gdk_spawn_on_screen() instead to ensure that
116  * the spawned program opens its windows on the right screen.
117  * </para></note>
118  *
119  * <note><para> Note that the returned @child_pid on Windows is a
120  * handle to the child process and not its identifier. Process handles
121  * and process identifiers are different concepts on Windows.
122  * </para></note>
123  *
124  * Return value: %TRUE on success, %FALSE if error is set
125  **/
126 gboolean
127 g_spawn_async (const gchar          *working_directory,
128                gchar               **argv,
129                gchar               **envp,
130                GSpawnFlags           flags,
131                GSpawnChildSetupFunc  child_setup,
132                gpointer              user_data,
133                GPid                 *child_pid,
134                GError              **error)
135 {
136   g_return_val_if_fail (argv != NULL, FALSE);
137   
138   return g_spawn_async_with_pipes (working_directory,
139                                    argv, envp,
140                                    flags,
141                                    child_setup,
142                                    user_data,
143                                    child_pid,
144                                    NULL, NULL, NULL,
145                                    error);
146 }
147
148 /* Avoids a danger in threaded situations (calling close()
149  * on a file descriptor twice, and another thread has
150  * re-opened it since the first close)
151  */
152 static gint
153 close_and_invalidate (gint *fd)
154 {
155   gint ret;
156
157   if (*fd < 0)
158     return -1;
159   else
160     {
161     again:
162       ret = close (*fd);
163       if (ret == -1 && errno == EINTR)
164         goto again;
165       *fd = -1;
166     }
167
168   return ret;
169 }
170
171 /* Some versions of OS X define READ_OK in public headers */
172 #undef READ_OK
173
174 typedef enum
175 {
176   READ_FAILED = 0, /* FALSE */
177   READ_OK,
178   READ_EOF
179 } ReadResult;
180
181 static ReadResult
182 read_data (GString *str,
183            gint     fd,
184            GError **error)
185 {
186   gssize bytes;
187   gchar buf[4096];
188
189  again:
190   bytes = read (fd, buf, 4096);
191
192   if (bytes == 0)
193     return READ_EOF;
194   else if (bytes > 0)
195     {
196       g_string_append_len (str, buf, bytes);
197       return READ_OK;
198     }
199   else if (errno == EINTR)
200     goto again;
201   else
202     {
203       int errsv = errno;
204
205       g_set_error (error,
206                    G_SPAWN_ERROR,
207                    G_SPAWN_ERROR_READ,
208                    _("Failed to read data from child process (%s)"),
209                    g_strerror (errsv));
210
211       return READ_FAILED;
212     }
213 }
214
215 typedef struct {
216   GMainLoop *loop;
217   gint *status_p;
218 } SyncWaitpidData;
219
220 static void
221 on_sync_waitpid (GPid     pid,
222                  gint     status,
223                  gpointer user_data)
224 {
225   SyncWaitpidData *data = user_data;
226   *(data->status_p) = status;
227   g_main_loop_quit (data->loop);
228 }
229
230 /**
231  * g_spawn_sync:
232  * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
233  * @argv: (array zero-terminated=1): child's argument vector
234  * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
235  * @flags: flags from #GSpawnFlags
236  * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
237  * @user_data: (closure): user data for @child_setup
238  * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
239  * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
240  * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
241  * @error: return location for error, or %NULL
242  *
243  * Executes a child synchronously (waits for the child to exit before returning).
244  * All output from the child is stored in @standard_output and @standard_error,
245  * if those parameters are non-%NULL. Note that you must set the  
246  * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
247  * passing %NULL for @standard_output and @standard_error.
248  *
249  * If @exit_status is non-%NULL, the platform-specific exit status of
250  * the child is stored there; see the doucumentation of
251  * g_spawn_check_exit_status() for how to use and interpret this.
252  * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
253  * @flags.
254  *
255  * If an error occurs, no data is returned in @standard_output,
256  * @standard_error, or @exit_status.
257  *
258  * This function calls g_spawn_async_with_pipes() internally; see that
259  * function for full details on the other parameters and details on
260  * how these functions work on Windows.
261  * 
262  * Return value: %TRUE on success, %FALSE if an error was set.
263  **/
264 gboolean
265 g_spawn_sync (const gchar          *working_directory,
266               gchar               **argv,
267               gchar               **envp,
268               GSpawnFlags           flags,
269               GSpawnChildSetupFunc  child_setup,
270               gpointer              user_data,
271               gchar               **standard_output,
272               gchar               **standard_error,
273               gint                 *exit_status,
274               GError              **error)     
275 {
276   gint outpipe = -1;
277   gint errpipe = -1;
278   GPid pid;
279   fd_set fds;
280   gint ret;
281   GString *outstr = NULL;
282   GString *errstr = NULL;
283   gboolean failed;
284   gint status;
285   SyncWaitpidData waitpid_data;
286   
287   g_return_val_if_fail (argv != NULL, FALSE);
288   g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
289   g_return_val_if_fail (standard_output == NULL ||
290                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
291   g_return_val_if_fail (standard_error == NULL ||
292                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
293   
294   /* Just to ensure segfaults if callers try to use
295    * these when an error is reported.
296    */
297   if (standard_output)
298     *standard_output = NULL;
299
300   if (standard_error)
301     *standard_error = NULL;
302   
303   if (!fork_exec_with_pipes (FALSE,
304                              working_directory,
305                              argv,
306                              envp,
307                              !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
308                              (flags & G_SPAWN_SEARCH_PATH) != 0,
309                              (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
310                              (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
311                              (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
312                              (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
313                              (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
314                              (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
315                              child_setup,
316                              user_data,
317                              &pid,
318                              NULL,
319                              standard_output ? &outpipe : NULL,
320                              standard_error ? &errpipe : NULL,
321                              error))
322     return FALSE;
323
324   /* Read data from child. */
325   
326   failed = FALSE;
327
328   if (outpipe >= 0)
329     {
330       outstr = g_string_new (NULL);
331     }
332       
333   if (errpipe >= 0)
334     {
335       errstr = g_string_new (NULL);
336     }
337
338   /* Read data until we get EOF on both pipes. */
339   while (!failed &&
340          (outpipe >= 0 ||
341           errpipe >= 0))
342     {
343       ret = 0;
344           
345       FD_ZERO (&fds);
346       if (outpipe >= 0)
347         FD_SET (outpipe, &fds);
348       if (errpipe >= 0)
349         FD_SET (errpipe, &fds);
350           
351       ret = select (MAX (outpipe, errpipe) + 1,
352                     &fds,
353                     NULL, NULL,
354                     NULL /* no timeout */);
355
356       if (ret < 0)
357         {
358           int errsv = errno;
359
360           if (errno == EINTR)
361             continue;
362
363           failed = TRUE;
364
365           g_set_error (error,
366                        G_SPAWN_ERROR,
367                        G_SPAWN_ERROR_READ,
368                        _("Unexpected error in select() reading data from a child process (%s)"),
369                        g_strerror (errsv));
370               
371           break;
372         }
373
374       if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
375         {
376           switch (read_data (outstr, outpipe, error))
377             {
378             case READ_FAILED:
379               failed = TRUE;
380               break;
381             case READ_EOF:
382               close_and_invalidate (&outpipe);
383               outpipe = -1;
384               break;
385             default:
386               break;
387             }
388
389           if (failed)
390             break;
391         }
392
393       if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
394         {
395           switch (read_data (errstr, errpipe, error))
396             {
397             case READ_FAILED:
398               failed = TRUE;
399               break;
400             case READ_EOF:
401               close_and_invalidate (&errpipe);
402               errpipe = -1;
403               break;
404             default:
405               break;
406             }
407
408           if (failed)
409             break;
410         }
411     }
412
413   /* These should only be open still if we had an error.  */
414   
415   if (outpipe >= 0)
416     close_and_invalidate (&outpipe);
417   if (errpipe >= 0)
418     close_and_invalidate (&errpipe);
419
420   /* Now create a temporary main context and loop, with just one
421    * waitpid source.  We used to invoke waitpid() directly here, but
422    * this way we unify with the worker thread in gmain.c.
423    */
424   {
425     GMainContext *context;
426     GMainLoop *loop;
427     GSource *source;
428
429     context = g_main_context_new ();
430     loop = g_main_loop_new (context, TRUE);
431
432     waitpid_data.loop = loop;
433     waitpid_data.status_p = &status;
434     
435     source = g_child_watch_source_new (pid);
436     g_source_set_callback (source, (GSourceFunc)on_sync_waitpid, &waitpid_data, NULL);
437     g_source_attach (source, context);
438     g_source_unref (source);
439     
440     g_main_loop_run (loop);
441
442     g_main_context_unref (context);
443     g_main_loop_unref (loop);
444   }
445   
446   if (failed)
447     {
448       if (outstr)
449         g_string_free (outstr, TRUE);
450       if (errstr)
451         g_string_free (errstr, TRUE);
452
453       return FALSE;
454     }
455   else
456     {
457       if (exit_status)
458         *exit_status = status;
459       
460       if (standard_output)        
461         *standard_output = g_string_free (outstr, FALSE);
462
463       if (standard_error)
464         *standard_error = g_string_free (errstr, FALSE);
465
466       return TRUE;
467     }
468 }
469
470 /**
471  * g_spawn_async_with_pipes:
472  * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
473  * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
474  * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
475  * @flags: flags from #GSpawnFlags
476  * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
477  * @user_data: (closure): user data for @child_setup
478  * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
479  * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
480  * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
481  * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
482  * @error: return location for error
483  *
484  * Executes a child program asynchronously (your program will not
485  * block waiting for the child to exit). The child program is
486  * specified by the only argument that must be provided, @argv. @argv
487  * should be a %NULL-terminated array of strings, to be passed as the
488  * argument vector for the child. The first string in @argv is of
489  * course the name of the program to execute. By default, the name of
490  * the program must be a full path. If @flags contains the 
491  * %G_SPAWN_SEARCH_PATH flag, the <envar>PATH</envar> environment variable 
492  * is used to search for the executable. If @flags contains the
493  * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the <envar>PATH</envar> variable from 
494  * @envp is used to search for the executable.
495  * If both the %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
496  * flags are set, the <envar>PATH</envar> variable from @envp takes precedence 
497  * over the environment variable.
498  *
499  * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
500  * used, then the program will be run from the current directory (or
501  * @working_directory, if specified); this might be unexpected or even
502  * dangerous in some cases when the current directory is world-writable.
503  *
504  * On Windows, note that all the string or string vector arguments to
505  * this function and the other g_spawn*() functions are in UTF-8, the
506  * GLib file name encoding. Unicode characters that are not part of
507  * the system codepage passed in these arguments will be correctly
508  * available in the spawned program only if it uses wide character API
509  * to retrieve its command line. For C programs built with Microsoft's
510  * tools it is enough to make the program have a wmain() instead of
511  * main(). wmain() has a wide character argument vector as parameter.
512  *
513  * At least currently, mingw doesn't support wmain(), so if you use
514  * mingw to develop the spawned program, it will have to call the
515  * undocumented function __wgetmainargs() to get the wide character
516  * argument vector and environment. See gspawn-win32-helper.c in the
517  * GLib sources or init.c in the mingw runtime sources for a prototype
518  * for that function. Alternatively, you can retrieve the Win32 system
519  * level wide character command line passed to the spawned program
520  * using the GetCommandLineW() function.
521  *
522  * On Windows the low-level child process creation API
523  * <function>CreateProcess()</function> doesn't use argument vectors,
524  * but a command line. The C runtime library's
525  * <function>spawn*()</function> family of functions (which
526  * g_spawn_async_with_pipes() eventually calls) paste the argument
527  * vector elements together into a command line, and the C runtime startup code
528  * does a corresponding reconstruction of an argument vector from the
529  * command line, to be passed to main(). Complications arise when you have
530  * argument vector elements that contain spaces of double quotes. The
531  * <function>spawn*()</function> functions don't do any quoting or
532  * escaping, but on the other hand the startup code does do unquoting
533  * and unescaping in order to enable receiving arguments with embedded
534  * spaces or double quotes. To work around this asymmetry,
535  * g_spawn_async_with_pipes() will do quoting and escaping on argument
536  * vector elements that need it before calling the C runtime
537  * spawn() function.
538  *
539  * The returned @child_pid on Windows is a handle to the child
540  * process, not its identifier. Process handles and process
541  * identifiers are different concepts on Windows.
542  *
543  * @envp is a %NULL-terminated array of strings, where each string
544  * has the form <literal>KEY=VALUE</literal>. This will become
545  * the child's environment. If @envp is %NULL, the child inherits its
546  * parent's environment.
547  *
548  * @flags should be the bitwise OR of any flags you want to affect the
549  * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
550  * child will not automatically be reaped; you must use a child watch to
551  * be notified about the death of the child process. Eventually you must
552  * call g_spawn_close_pid() on the @child_pid, in order to free
553  * resources which may be associated with the child process. (On Unix,
554  * using a child watch is equivalent to calling waitpid() or handling
555  * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
556  * is equivalent to calling CloseHandle() on the process handle returned
557  * in @child_pid).  See g_child_watch_add().
558  *
559  * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
560  * descriptors will be inherited by the child; otherwise all
561  * descriptors except stdin/stdout/stderr will be closed before
562  * calling exec() in the child. %G_SPAWN_SEARCH_PATH 
563  * means that <literal>argv[0]</literal> need not be an absolute path, it
564  * will be looked for in the <envar>PATH</envar> environment variable.
565  * %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an absolute path, it
566  * will be looked for in the <envar>PATH</envar> variable from @envp. If
567  * both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP are used,
568  * the value from @envp takes precedence over the environment.
569  * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will 
570  * be discarded, instead of going to the same location as the parent's 
571  * standard output. If you use this flag, @standard_output must be %NULL.
572  * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
573  * will be discarded, instead of going to the same location as the parent's
574  * standard error. If you use this flag, @standard_error must be %NULL.
575  * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
576  * standard input (by default, the child's standard input is attached to
577  * /dev/null). If you use this flag, @standard_input must be %NULL.
578  * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
579  * the file to execute, while the remaining elements are the
580  * actual argument vector to pass to the file. Normally
581  * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
582  * passes all of @argv to the child.
583  *
584  * @child_setup and @user_data are a function and user data. On POSIX
585  * platforms, the function is called in the child after GLib has
586  * performed all the setup it plans to perform (including creating
587  * pipes, closing file descriptors, etc.) but before calling
588  * exec(). That is, @child_setup is called just
589  * before calling exec() in the child. Obviously
590  * actions taken in this function will only affect the child, not the
591  * parent.
592  *
593  * On Windows, there is no separate fork() and exec()
594  * functionality. Child processes are created and run with a single
595  * API call, CreateProcess(). There is no sensible thing @child_setup
596  * could be used for on Windows so it is ignored and not called.
597  *
598  * If non-%NULL, @child_pid will on Unix be filled with the child's
599  * process ID. You can use the process ID to send signals to the
600  * child, or to use g_child_watch_add() (or waitpid()) if you specified the
601  * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
602  * filled with a handle to the child process only if you specified the
603  * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
604  * process using the Win32 API, for example wait for its termination
605  * with the <function>WaitFor*()</function> functions, or examine its
606  * exit code with GetExitCodeProcess(). You should close the handle 
607  * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
608  *
609  * If non-%NULL, the @standard_input, @standard_output, @standard_error
610  * locations will be filled with file descriptors for writing to the child's
611  * standard input or reading from its standard output or standard error.
612  * The caller of g_spawn_async_with_pipes() must close these file descriptors
613  * when they are no longer in use. If these parameters are %NULL, the corresponding
614  * pipe won't be created.
615  *
616  * If @standard_input is NULL, the child's standard input is attached to 
617  * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
618  *
619  * If @standard_error is NULL, the child's standard error goes to the same 
620  * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL 
621  * is set.
622  *
623  * If @standard_output is NULL, the child's standard output goes to the same 
624  * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL 
625  * is set.
626  *
627  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
628  * If an error is set, the function returns %FALSE. Errors
629  * are reported even if they occur in the child (for example if the
630  * executable in <literal>argv[0]</literal> is not found). Typically
631  * the <literal>message</literal> field of returned errors should be displayed
632  * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
633  *
634  * If an error occurs, @child_pid, @standard_input, @standard_output,
635  * and @standard_error will not be filled with valid values.
636  *
637  * If @child_pid is not %NULL and an error does not occur then the returned
638  * process reference must be closed using g_spawn_close_pid().
639  *
640  * <note><para>
641  * If you are writing a GTK+ application, and the program you 
642  * are spawning is a graphical application, too, then you may
643  * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
644  * the spawned program opens its windows on the right screen.
645  * </para></note>
646  * 
647  * Return value: %TRUE on success, %FALSE if an error was set
648  **/
649 gboolean
650 g_spawn_async_with_pipes (const gchar          *working_directory,
651                           gchar               **argv,
652                           gchar               **envp,
653                           GSpawnFlags           flags,
654                           GSpawnChildSetupFunc  child_setup,
655                           gpointer              user_data,
656                           GPid                 *child_pid,
657                           gint                 *standard_input,
658                           gint                 *standard_output,
659                           gint                 *standard_error,
660                           GError              **error)
661 {
662   g_return_val_if_fail (argv != NULL, FALSE);
663   g_return_val_if_fail (standard_output == NULL ||
664                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
665   g_return_val_if_fail (standard_error == NULL ||
666                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
667   /* can't inherit stdin if we have an input pipe. */
668   g_return_val_if_fail (standard_input == NULL ||
669                         !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
670   
671   return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
672                                working_directory,
673                                argv,
674                                envp,
675                                !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
676                                (flags & G_SPAWN_SEARCH_PATH) != 0,
677                                (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
678                                (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
679                                (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
680                                (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
681                                (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
682                                (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
683                                child_setup,
684                                user_data,
685                                child_pid,
686                                standard_input,
687                                standard_output,
688                                standard_error,
689                                error);
690 }
691
692 /**
693  * g_spawn_command_line_sync:
694  * @command_line: a command line 
695  * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
696  * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
697  * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
698  * @error: return location for errors
699  *
700  * A simple version of g_spawn_sync() with little-used parameters
701  * removed, taking a command line instead of an argument vector.  See
702  * g_spawn_sync() for full details. @command_line will be parsed by
703  * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
704  * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
705  * implications, so consider using g_spawn_sync() directly if
706  * appropriate. Possible errors are those from g_spawn_sync() and those
707  * from g_shell_parse_argv().
708  *
709  * If @exit_status is non-%NULL, the platform-specific exit status of
710  * the child is stored there; see the documentation of
711  * g_spawn_check_exit_status() for how to use and interpret this.
712  * 
713  * On Windows, please note the implications of g_shell_parse_argv()
714  * parsing @command_line. Parsing is done according to Unix shell rules, not 
715  * Windows command interpreter rules.
716  * Space is a separator, and backslashes are
717  * special. Thus you cannot simply pass a @command_line containing
718  * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
719  * the backslashes will be eaten, and the space will act as a
720  * separator. You need to enclose such paths with single quotes, like
721  * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
722  *
723  * Return value: %TRUE on success, %FALSE if an error was set
724  **/
725 gboolean
726 g_spawn_command_line_sync (const gchar  *command_line,
727                            gchar       **standard_output,
728                            gchar       **standard_error,
729                            gint         *exit_status,
730                            GError      **error)
731 {
732   gboolean retval;
733   gchar **argv = NULL;
734
735   g_return_val_if_fail (command_line != NULL, FALSE);
736   
737   if (!g_shell_parse_argv (command_line,
738                            NULL, &argv,
739                            error))
740     return FALSE;
741   
742   retval = g_spawn_sync (NULL,
743                          argv,
744                          NULL,
745                          G_SPAWN_SEARCH_PATH,
746                          NULL,
747                          NULL,
748                          standard_output,
749                          standard_error,
750                          exit_status,
751                          error);
752   g_strfreev (argv);
753
754   return retval;
755 }
756
757 /**
758  * g_spawn_command_line_async:
759  * @command_line: a command line
760  * @error: return location for errors
761  * 
762  * A simple version of g_spawn_async() that parses a command line with
763  * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
764  * command line in the background. Unlike g_spawn_async(), the
765  * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
766  * that %G_SPAWN_SEARCH_PATH can have security implications, so
767  * consider using g_spawn_async() directly if appropriate. Possible
768  * errors are those from g_shell_parse_argv() and g_spawn_async().
769  * 
770  * The same concerns on Windows apply as for g_spawn_command_line_sync().
771  *
772  * Return value: %TRUE on success, %FALSE if error is set.
773  **/
774 gboolean
775 g_spawn_command_line_async (const gchar *command_line,
776                             GError     **error)
777 {
778   gboolean retval;
779   gchar **argv = NULL;
780
781   g_return_val_if_fail (command_line != NULL, FALSE);
782
783   if (!g_shell_parse_argv (command_line,
784                            NULL, &argv,
785                            error))
786     return FALSE;
787   
788   retval = g_spawn_async (NULL,
789                           argv,
790                           NULL,
791                           G_SPAWN_SEARCH_PATH,
792                           NULL,
793                           NULL,
794                           NULL,
795                           error);
796   g_strfreev (argv);
797
798   return retval;
799 }
800
801 /**
802  * g_spawn_check_exit_status:
803  * @exit_status: An exit code as returned from g_spawn_sync()
804  * @error: a #GError
805  *
806  * Set @error if @exit_status indicates the child exited abnormally
807  * (e.g. with a nonzero exit code, or via a fatal signal).
808  *
809  * The g_spawn_sync() and g_child_watch_add() family of APIs return an
810  * exit status for subprocesses encoded in a platform-specific way.
811  * On Unix, this is guaranteed to be in the same format
812  * <literal>waitpid(2)</literal> returns, and on Windows it is
813  * guaranteed to be the result of
814  * <literal>GetExitCodeProcess()</literal>.  Prior to the introduction
815  * of this function in GLib 2.34, interpreting @exit_status required
816  * use of platform-specific APIs, which is problematic for software
817  * using GLib as a cross-platform layer.
818  *
819  * Additionally, many programs simply want to determine whether or not
820  * the child exited successfully, and either propagate a #GError or
821  * print a message to standard error.  In that common case, this
822  * function can be used.  Note that the error message in @error will
823  * contain human-readable information about the exit status.
824  *
825  * The <literal>domain</literal> and <literal>code</literal> of @error
826  * have special semantics in the case where the process has an "exit
827  * code", as opposed to being killed by a signal.  On Unix, this
828  * happens if <literal>WIFEXITED</literal> would be true of
829  * @exit_status.  On Windows, it is always the case.
830  *
831  * The special semantics are that the actual exit code will be the
832  * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
833  * This allows you to differentiate between different exit codes.
834  *
835  * If the process was terminated by some means other than an exit
836  * status, the domain will be %G_SPAWN_ERROR, and the code will be
837  * %G_SPAWN_ERROR_FAILED.
838  *
839  * This function just offers convenience; you can of course also check
840  * the available platform via a macro such as %G_OS_UNIX, and use
841  * <literal>WIFEXITED()</literal> and <literal>WEXITSTATUS()</literal>
842  * on @exit_status directly.  Do not attempt to scan or parse the
843  * error message string; it may be translated and/or change in future
844  * versions of GLib.
845  *
846  * Returns: %TRUE if child exited successfully, %FALSE otherwise (and @error will be set)
847  * Since: 2.34
848  */
849 gboolean
850 g_spawn_check_exit_status (gint      exit_status,
851                            GError  **error)
852 {
853   gboolean ret = FALSE;
854
855   if (WIFEXITED (exit_status))
856     {
857       if (WEXITSTATUS (exit_status) != 0)
858         {
859           g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
860                        _("Child process exited with code %ld"),
861                        (long) WEXITSTATUS (exit_status));
862           goto out;
863         }
864     }
865   else if (WIFSIGNALED (exit_status))
866     {
867       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
868                    _("Child process killed by signal %ld"),
869                    (long) WTERMSIG (exit_status));
870       goto out;
871     }
872   else if (WIFSTOPPED (exit_status))
873     {
874       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
875                    _("Child process stopped by signal %ld"),
876                    (long) WSTOPSIG (exit_status));
877       goto out;
878     }
879   else
880     {
881       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
882                    _("Child process exited abnormally"));
883       goto out;
884     }
885
886   ret = TRUE;
887  out:
888   return ret;
889 }
890
891 static gint
892 exec_err_to_g_error (gint en)
893 {
894   switch (en)
895     {
896 #ifdef EACCES
897     case EACCES:
898       return G_SPAWN_ERROR_ACCES;
899       break;
900 #endif
901
902 #ifdef EPERM
903     case EPERM:
904       return G_SPAWN_ERROR_PERM;
905       break;
906 #endif
907
908 #ifdef E2BIG
909     case E2BIG:
910       return G_SPAWN_ERROR_TOO_BIG;
911       break;
912 #endif
913
914 #ifdef ENOEXEC
915     case ENOEXEC:
916       return G_SPAWN_ERROR_NOEXEC;
917       break;
918 #endif
919
920 #ifdef ENAMETOOLONG
921     case ENAMETOOLONG:
922       return G_SPAWN_ERROR_NAMETOOLONG;
923       break;
924 #endif
925
926 #ifdef ENOENT
927     case ENOENT:
928       return G_SPAWN_ERROR_NOENT;
929       break;
930 #endif
931
932 #ifdef ENOMEM
933     case ENOMEM:
934       return G_SPAWN_ERROR_NOMEM;
935       break;
936 #endif
937
938 #ifdef ENOTDIR
939     case ENOTDIR:
940       return G_SPAWN_ERROR_NOTDIR;
941       break;
942 #endif
943
944 #ifdef ELOOP
945     case ELOOP:
946       return G_SPAWN_ERROR_LOOP;
947       break;
948 #endif
949       
950 #ifdef ETXTBUSY
951     case ETXTBUSY:
952       return G_SPAWN_ERROR_TXTBUSY;
953       break;
954 #endif
955
956 #ifdef EIO
957     case EIO:
958       return G_SPAWN_ERROR_IO;
959       break;
960 #endif
961
962 #ifdef ENFILE
963     case ENFILE:
964       return G_SPAWN_ERROR_NFILE;
965       break;
966 #endif
967
968 #ifdef EMFILE
969     case EMFILE:
970       return G_SPAWN_ERROR_MFILE;
971       break;
972 #endif
973
974 #ifdef EINVAL
975     case EINVAL:
976       return G_SPAWN_ERROR_INVAL;
977       break;
978 #endif
979
980 #ifdef EISDIR
981     case EISDIR:
982       return G_SPAWN_ERROR_ISDIR;
983       break;
984 #endif
985
986 #ifdef ELIBBAD
987     case ELIBBAD:
988       return G_SPAWN_ERROR_LIBBAD;
989       break;
990 #endif
991       
992     default:
993       return G_SPAWN_ERROR_FAILED;
994       break;
995     }
996 }
997
998 static gssize
999 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1000 {
1001   gchar *buf = (gchar *) vbuf;
1002   
1003   while (to_write > 0)
1004     {
1005       gssize count = write (fd, buf, to_write);
1006       if (count < 0)
1007         {
1008           if (errno != EINTR)
1009             return FALSE;
1010         }
1011       else
1012         {
1013           to_write -= count;
1014           buf += count;
1015         }
1016     }
1017   
1018   return TRUE;
1019 }
1020
1021 G_GNUC_NORETURN
1022 static void
1023 write_err_and_exit (gint fd, gint msg)
1024 {
1025   gint en = errno;
1026   
1027   write_all (fd, &msg, sizeof(msg));
1028   write_all (fd, &en, sizeof(en));
1029   
1030   _exit (1);
1031 }
1032
1033 static int
1034 set_cloexec (void *data, gint fd)
1035 {
1036   if (fd >= GPOINTER_TO_INT (data))
1037     fcntl (fd, F_SETFD, FD_CLOEXEC);
1038
1039   return 0;
1040 }
1041
1042 #ifndef HAVE_FDWALK
1043 static int
1044 fdwalk (int (*cb)(void *data, int fd), void *data)
1045 {
1046   gint open_max;
1047   gint fd;
1048   gint res = 0;
1049   
1050 #ifdef HAVE_SYS_RESOURCE_H
1051   struct rlimit rl;
1052 #endif
1053
1054 #ifdef __linux__  
1055   DIR *d;
1056
1057   if ((d = opendir("/proc/self/fd"))) {
1058       struct dirent *de;
1059
1060       while ((de = readdir(d))) {
1061           glong l;
1062           gchar *e = NULL;
1063
1064           if (de->d_name[0] == '.')
1065               continue;
1066             
1067           errno = 0;
1068           l = strtol(de->d_name, &e, 10);
1069           if (errno != 0 || !e || *e)
1070               continue;
1071
1072           fd = (gint) l;
1073
1074           if ((glong) fd != l)
1075               continue;
1076
1077           if (fd == dirfd(d))
1078               continue;
1079
1080           if ((res = cb (data, fd)) != 0)
1081               break;
1082         }
1083       
1084       closedir(d);
1085       return res;
1086   }
1087
1088   /* If /proc is not mounted or not accessible we fall back to the old
1089    * rlimit trick */
1090
1091 #endif
1092   
1093 #ifdef HAVE_SYS_RESOURCE_H
1094       
1095   if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1096       open_max = rl.rlim_max;
1097   else
1098 #endif
1099       open_max = sysconf (_SC_OPEN_MAX);
1100
1101   for (fd = 0; fd < open_max; fd++)
1102       if ((res = cb (data, fd)) != 0)
1103           break;
1104
1105   return res;
1106 }
1107 #endif
1108
1109 static gint
1110 sane_dup2 (gint fd1, gint fd2)
1111 {
1112   gint ret;
1113
1114  retry:
1115   ret = dup2 (fd1, fd2);
1116   if (ret < 0 && errno == EINTR)
1117     goto retry;
1118
1119   return ret;
1120 }
1121
1122 static gint
1123 sane_open (const char *path, gint mode)
1124 {
1125   gint ret;
1126
1127  retry:
1128   ret = open (path, mode);
1129   if (ret < 0 && errno == EINTR)
1130     goto retry;
1131
1132   return ret;
1133 }
1134
1135 enum
1136 {
1137   CHILD_CHDIR_FAILED,
1138   CHILD_EXEC_FAILED,
1139   CHILD_DUP2_FAILED,
1140   CHILD_FORK_FAILED
1141 };
1142
1143 static void
1144 do_exec (gint                  child_err_report_fd,
1145          gint                  stdin_fd,
1146          gint                  stdout_fd,
1147          gint                  stderr_fd,
1148          const gchar          *working_directory,
1149          gchar               **argv,
1150          gchar               **envp,
1151          gboolean              close_descriptors,
1152          gboolean              search_path,
1153          gboolean              search_path_from_envp,
1154          gboolean              stdout_to_null,
1155          gboolean              stderr_to_null,
1156          gboolean              child_inherits_stdin,
1157          gboolean              file_and_argv_zero,
1158          GSpawnChildSetupFunc  child_setup,
1159          gpointer              user_data)
1160 {
1161   if (working_directory && chdir (working_directory) < 0)
1162     write_err_and_exit (child_err_report_fd,
1163                         CHILD_CHDIR_FAILED);
1164
1165   /* Close all file descriptors but stdin stdout and stderr as
1166    * soon as we exec. Note that this includes
1167    * child_err_report_fd, which keeps the parent from blocking
1168    * forever on the other end of that pipe.
1169    */
1170   if (close_descriptors)
1171     {
1172       fdwalk (set_cloexec, GINT_TO_POINTER(3));
1173     }
1174   else
1175     {
1176       /* We need to do child_err_report_fd anyway */
1177       set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1178     }
1179   
1180   /* Redirect pipes as required */
1181   
1182   if (stdin_fd >= 0)
1183     {
1184       /* dup2 can't actually fail here I don't think */
1185           
1186       if (sane_dup2 (stdin_fd, 0) < 0)
1187         write_err_and_exit (child_err_report_fd,
1188                             CHILD_DUP2_FAILED);
1189
1190       /* ignore this if it doesn't work */
1191       close_and_invalidate (&stdin_fd);
1192     }
1193   else if (!child_inherits_stdin)
1194     {
1195       /* Keep process from blocking on a read of stdin */
1196       gint read_null = open ("/dev/null", O_RDONLY);
1197       g_assert (read_null != -1);
1198       sane_dup2 (read_null, 0);
1199       close_and_invalidate (&read_null);
1200     }
1201
1202   if (stdout_fd >= 0)
1203     {
1204       /* dup2 can't actually fail here I don't think */
1205           
1206       if (sane_dup2 (stdout_fd, 1) < 0)
1207         write_err_and_exit (child_err_report_fd,
1208                             CHILD_DUP2_FAILED);
1209
1210       /* ignore this if it doesn't work */
1211       close_and_invalidate (&stdout_fd);
1212     }
1213   else if (stdout_to_null)
1214     {
1215       gint write_null = sane_open ("/dev/null", O_WRONLY);
1216       g_assert (write_null != -1);
1217       sane_dup2 (write_null, 1);
1218       close_and_invalidate (&write_null);
1219     }
1220
1221   if (stderr_fd >= 0)
1222     {
1223       /* dup2 can't actually fail here I don't think */
1224           
1225       if (sane_dup2 (stderr_fd, 2) < 0)
1226         write_err_and_exit (child_err_report_fd,
1227                             CHILD_DUP2_FAILED);
1228
1229       /* ignore this if it doesn't work */
1230       close_and_invalidate (&stderr_fd);
1231     }
1232   else if (stderr_to_null)
1233     {
1234       gint write_null = sane_open ("/dev/null", O_WRONLY);
1235       sane_dup2 (write_null, 2);
1236       close_and_invalidate (&write_null);
1237     }
1238   
1239   /* Call user function just before we exec */
1240   if (child_setup)
1241     {
1242       (* child_setup) (user_data);
1243     }
1244
1245   g_execute (argv[0],
1246              file_and_argv_zero ? argv + 1 : argv,
1247              envp, search_path, search_path_from_envp);
1248
1249   /* Exec failed */
1250   write_err_and_exit (child_err_report_fd,
1251                       CHILD_EXEC_FAILED);
1252 }
1253
1254 static gboolean
1255 read_ints (int      fd,
1256            gint*    buf,
1257            gint     n_ints_in_buf,    
1258            gint    *n_ints_read,      
1259            GError **error)
1260 {
1261   gsize bytes = 0;    
1262   
1263   while (TRUE)
1264     {
1265       gssize chunk;    
1266
1267       if (bytes >= sizeof(gint)*2)
1268         break; /* give up, who knows what happened, should not be
1269                 * possible.
1270                 */
1271           
1272     again:
1273       chunk = read (fd,
1274                     ((gchar*)buf) + bytes,
1275                     sizeof(gint) * n_ints_in_buf - bytes);
1276       if (chunk < 0 && errno == EINTR)
1277         goto again;
1278           
1279       if (chunk < 0)
1280         {
1281           int errsv = errno;
1282
1283           /* Some weird shit happened, bail out */
1284           g_set_error (error,
1285                        G_SPAWN_ERROR,
1286                        G_SPAWN_ERROR_FAILED,
1287                        _("Failed to read from child pipe (%s)"),
1288                        g_strerror (errsv));
1289
1290           return FALSE;
1291         }
1292       else if (chunk == 0)
1293         break; /* EOF */
1294       else /* chunk > 0 */
1295         bytes += chunk;
1296     }
1297
1298   *n_ints_read = (gint)(bytes / sizeof(gint));
1299
1300   return TRUE;
1301 }
1302
1303 static gboolean
1304 fork_exec_with_pipes (gboolean              intermediate_child,
1305                       const gchar          *working_directory,
1306                       gchar               **argv,
1307                       gchar               **envp,
1308                       gboolean              close_descriptors,
1309                       gboolean              search_path,
1310                       gboolean              search_path_from_envp,
1311                       gboolean              stdout_to_null,
1312                       gboolean              stderr_to_null,
1313                       gboolean              child_inherits_stdin,
1314                       gboolean              file_and_argv_zero,
1315                       gboolean              cloexec_pipes,
1316                       GSpawnChildSetupFunc  child_setup,
1317                       gpointer              user_data,
1318                       GPid                 *child_pid,
1319                       gint                 *standard_input,
1320                       gint                 *standard_output,
1321                       gint                 *standard_error,
1322                       GError              **error)     
1323 {
1324   GPid pid = -1;
1325   gint stdin_pipe[2] = { -1, -1 };
1326   gint stdout_pipe[2] = { -1, -1 };
1327   gint stderr_pipe[2] = { -1, -1 };
1328   gint child_err_report_pipe[2] = { -1, -1 };
1329   gint child_pid_report_pipe[2] = { -1, -1 };
1330   guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1331   gint status;
1332   
1333   if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1334     return FALSE;
1335
1336   if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1337     goto cleanup_and_fail;
1338   
1339   if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1340     goto cleanup_and_fail;
1341   
1342   if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1343     goto cleanup_and_fail;
1344
1345   if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1346     goto cleanup_and_fail;
1347
1348   pid = fork ();
1349
1350   if (pid < 0)
1351     {
1352       int errsv = errno;
1353
1354       g_set_error (error,
1355                    G_SPAWN_ERROR,
1356                    G_SPAWN_ERROR_FORK,
1357                    _("Failed to fork (%s)"),
1358                    g_strerror (errsv));
1359
1360       goto cleanup_and_fail;
1361     }
1362   else if (pid == 0)
1363     {
1364       /* Immediate child. This may or may not be the child that
1365        * actually execs the new process.
1366        */
1367
1368       /* Reset some signal handlers that we may use */
1369       signal (SIGCHLD, SIG_DFL);
1370       signal (SIGINT, SIG_DFL);
1371       signal (SIGTERM, SIG_DFL);
1372       signal (SIGHUP, SIG_DFL);
1373       
1374       /* Be sure we crash if the parent exits
1375        * and we write to the err_report_pipe
1376        */
1377       signal (SIGPIPE, SIG_DFL);
1378
1379       /* Close the parent's end of the pipes;
1380        * not needed in the close_descriptors case,
1381        * though
1382        */
1383       close_and_invalidate (&child_err_report_pipe[0]);
1384       close_and_invalidate (&child_pid_report_pipe[0]);
1385       close_and_invalidate (&stdin_pipe[1]);
1386       close_and_invalidate (&stdout_pipe[0]);
1387       close_and_invalidate (&stderr_pipe[0]);
1388       
1389       if (intermediate_child)
1390         {
1391           /* We need to fork an intermediate child that launches the
1392            * final child. The purpose of the intermediate child
1393            * is to exit, so we can waitpid() it immediately.
1394            * Then the grandchild will not become a zombie.
1395            */
1396           GPid grandchild_pid;
1397
1398           grandchild_pid = fork ();
1399
1400           if (grandchild_pid < 0)
1401             {
1402               /* report -1 as child PID */
1403               write_all (child_pid_report_pipe[1], &grandchild_pid,
1404                          sizeof(grandchild_pid));
1405               
1406               write_err_and_exit (child_err_report_pipe[1],
1407                                   CHILD_FORK_FAILED);              
1408             }
1409           else if (grandchild_pid == 0)
1410             {
1411               do_exec (child_err_report_pipe[1],
1412                        stdin_pipe[0],
1413                        stdout_pipe[1],
1414                        stderr_pipe[1],
1415                        working_directory,
1416                        argv,
1417                        envp,
1418                        close_descriptors,
1419                        search_path,
1420                        search_path_from_envp,
1421                        stdout_to_null,
1422                        stderr_to_null,
1423                        child_inherits_stdin,
1424                        file_and_argv_zero,
1425                        child_setup,
1426                        user_data);
1427             }
1428           else
1429             {
1430               write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1431               close_and_invalidate (&child_pid_report_pipe[1]);
1432               
1433               _exit (0);
1434             }
1435         }
1436       else
1437         {
1438           /* Just run the child.
1439            */
1440
1441           do_exec (child_err_report_pipe[1],
1442                    stdin_pipe[0],
1443                    stdout_pipe[1],
1444                    stderr_pipe[1],
1445                    working_directory,
1446                    argv,
1447                    envp,
1448                    close_descriptors,
1449                    search_path,
1450                    search_path_from_envp,
1451                    stdout_to_null,
1452                    stderr_to_null,
1453                    child_inherits_stdin,
1454                    file_and_argv_zero,
1455                    child_setup,
1456                    user_data);
1457         }
1458     }
1459   else
1460     {
1461       /* Parent */
1462       
1463       gint buf[2];
1464       gint n_ints = 0;    
1465
1466       /* Close the uncared-about ends of the pipes */
1467       close_and_invalidate (&child_err_report_pipe[1]);
1468       close_and_invalidate (&child_pid_report_pipe[1]);
1469       close_and_invalidate (&stdin_pipe[0]);
1470       close_and_invalidate (&stdout_pipe[1]);
1471       close_and_invalidate (&stderr_pipe[1]);
1472
1473       /* If we had an intermediate child, reap it */
1474       if (intermediate_child)
1475         {
1476         wait_again:
1477           if (waitpid (pid, &status, 0) < 0)
1478             {
1479               if (errno == EINTR)
1480                 goto wait_again;
1481               else if (errno == ECHILD)
1482                 ; /* do nothing, child already reaped */
1483               else
1484                 g_warning ("waitpid() should not fail in "
1485                            "'fork_exec_with_pipes'");
1486             }
1487         }
1488       
1489
1490       if (!read_ints (child_err_report_pipe[0],
1491                       buf, 2, &n_ints,
1492                       error))
1493         goto cleanup_and_fail;
1494         
1495       if (n_ints >= 2)
1496         {
1497           /* Error from the child. */
1498
1499           switch (buf[0])
1500             {
1501             case CHILD_CHDIR_FAILED:
1502               g_set_error (error,
1503                            G_SPAWN_ERROR,
1504                            G_SPAWN_ERROR_CHDIR,
1505                            _("Failed to change to directory '%s' (%s)"),
1506                            working_directory,
1507                            g_strerror (buf[1]));
1508
1509               break;
1510               
1511             case CHILD_EXEC_FAILED:
1512               g_set_error (error,
1513                            G_SPAWN_ERROR,
1514                            exec_err_to_g_error (buf[1]),
1515                            _("Failed to execute child process \"%s\" (%s)"),
1516                            argv[0],
1517                            g_strerror (buf[1]));
1518
1519               break;
1520               
1521             case CHILD_DUP2_FAILED:
1522               g_set_error (error,
1523                            G_SPAWN_ERROR,
1524                            G_SPAWN_ERROR_FAILED,
1525                            _("Failed to redirect output or input of child process (%s)"),
1526                            g_strerror (buf[1]));
1527
1528               break;
1529
1530             case CHILD_FORK_FAILED:
1531               g_set_error (error,
1532                            G_SPAWN_ERROR,
1533                            G_SPAWN_ERROR_FORK,
1534                            _("Failed to fork child process (%s)"),
1535                            g_strerror (buf[1]));
1536               break;
1537               
1538             default:
1539               g_set_error (error,
1540                            G_SPAWN_ERROR,
1541                            G_SPAWN_ERROR_FAILED,
1542                            _("Unknown error executing child process \"%s\""),
1543                            argv[0]);
1544               break;
1545             }
1546
1547           goto cleanup_and_fail;
1548         }
1549
1550       /* Get child pid from intermediate child pipe. */
1551       if (intermediate_child)
1552         {
1553           n_ints = 0;
1554           
1555           if (!read_ints (child_pid_report_pipe[0],
1556                           buf, 1, &n_ints, error))
1557             goto cleanup_and_fail;
1558
1559           if (n_ints < 1)
1560             {
1561               int errsv = errno;
1562
1563               g_set_error (error,
1564                            G_SPAWN_ERROR,
1565                            G_SPAWN_ERROR_FAILED,
1566                            _("Failed to read enough data from child pid pipe (%s)"),
1567                            g_strerror (errsv));
1568               goto cleanup_and_fail;
1569             }
1570           else
1571             {
1572               /* we have the child pid */
1573               pid = buf[0];
1574             }
1575         }
1576       
1577       /* Success against all odds! return the information */
1578       close_and_invalidate (&child_err_report_pipe[0]);
1579       close_and_invalidate (&child_pid_report_pipe[0]);
1580  
1581       if (child_pid)
1582         *child_pid = pid;
1583
1584       if (standard_input)
1585         *standard_input = stdin_pipe[1];
1586       if (standard_output)
1587         *standard_output = stdout_pipe[0];
1588       if (standard_error)
1589         *standard_error = stderr_pipe[0];
1590       
1591       return TRUE;
1592     }
1593
1594  cleanup_and_fail:
1595
1596   /* There was an error from the Child, reap the child to avoid it being
1597      a zombie.
1598    */
1599
1600   if (pid > 0)
1601   {
1602     wait_failed:
1603      if (waitpid (pid, NULL, 0) < 0)
1604        {
1605           if (errno == EINTR)
1606             goto wait_failed;
1607           else if (errno == ECHILD)
1608             ; /* do nothing, child already reaped */
1609           else
1610             g_warning ("waitpid() should not fail in "
1611                        "'fork_exec_with_pipes'");
1612        }
1613    }
1614
1615   close_and_invalidate (&child_err_report_pipe[0]);
1616   close_and_invalidate (&child_err_report_pipe[1]);
1617   close_and_invalidate (&child_pid_report_pipe[0]);
1618   close_and_invalidate (&child_pid_report_pipe[1]);
1619   close_and_invalidate (&stdin_pipe[0]);
1620   close_and_invalidate (&stdin_pipe[1]);
1621   close_and_invalidate (&stdout_pipe[0]);
1622   close_and_invalidate (&stdout_pipe[1]);
1623   close_and_invalidate (&stderr_pipe[0]);
1624   close_and_invalidate (&stderr_pipe[1]);
1625
1626   return FALSE;
1627 }
1628
1629 /* Based on execvp from GNU C Library */
1630
1631 static void
1632 script_execute (const gchar *file,
1633                 gchar      **argv,
1634                 gchar      **envp)
1635 {
1636   /* Count the arguments.  */
1637   int argc = 0;
1638   while (argv[argc])
1639     ++argc;
1640   
1641   /* Construct an argument list for the shell.  */
1642   {
1643     gchar **new_argv;
1644
1645     new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1646     
1647     new_argv[0] = (char *) "/bin/sh";
1648     new_argv[1] = (char *) file;
1649     while (argc > 0)
1650       {
1651         new_argv[argc + 1] = argv[argc];
1652         --argc;
1653       }
1654
1655     /* Execute the shell. */
1656     if (envp)
1657       execve (new_argv[0], new_argv, envp);
1658     else
1659       execv (new_argv[0], new_argv);
1660     
1661     g_free (new_argv);
1662   }
1663 }
1664
1665 static gchar*
1666 my_strchrnul (const gchar *str, gchar c)
1667 {
1668   gchar *p = (gchar*) str;
1669   while (*p && (*p != c))
1670     ++p;
1671
1672   return p;
1673 }
1674
1675 static gint
1676 g_execute (const gchar *file,
1677            gchar      **argv,
1678            gchar      **envp,
1679            gboolean     search_path,
1680            gboolean     search_path_from_envp)
1681 {
1682   if (*file == '\0')
1683     {
1684       /* We check the simple case first. */
1685       errno = ENOENT;
1686       return -1;
1687     }
1688
1689   if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1690     {
1691       /* Don't search when it contains a slash. */
1692       if (envp)
1693         execve (file, argv, envp);
1694       else
1695         execv (file, argv);
1696       
1697       if (errno == ENOEXEC)
1698         script_execute (file, argv, envp);
1699     }
1700   else
1701     {
1702       gboolean got_eacces = 0;
1703       const gchar *path, *p;
1704       gchar *name, *freeme;
1705       gsize len;
1706       gsize pathlen;
1707
1708       path = NULL;
1709       if (search_path_from_envp)
1710         path = g_environ_getenv (envp, "PATH");
1711       if (search_path && path == NULL)
1712         path = g_getenv ("PATH");
1713
1714       if (path == NULL)
1715         {
1716           /* There is no `PATH' in the environment.  The default
1717            * search path in libc is the current directory followed by
1718            * the path `confstr' returns for `_CS_PATH'.
1719            */
1720
1721           /* In GLib we put . last, for security, and don't use the
1722            * unportable confstr(); UNIX98 does not actually specify
1723            * what to search if PATH is unset. POSIX may, dunno.
1724            */
1725           
1726           path = "/bin:/usr/bin:.";
1727         }
1728
1729       len = strlen (file) + 1;
1730       pathlen = strlen (path);
1731       freeme = name = g_malloc (pathlen + len + 1);
1732       
1733       /* Copy the file name at the top, including '\0'  */
1734       memcpy (name + pathlen + 1, file, len);
1735       name = name + pathlen;
1736       /* And add the slash before the filename  */
1737       *name = '/';
1738
1739       p = path;
1740       do
1741         {
1742           char *startp;
1743
1744           path = p;
1745           p = my_strchrnul (path, ':');
1746
1747           if (p == path)
1748             /* Two adjacent colons, or a colon at the beginning or the end
1749              * of `PATH' means to search the current directory.
1750              */
1751             startp = name + 1;
1752           else
1753             startp = memcpy (name - (p - path), path, p - path);
1754
1755           /* Try to execute this name.  If it works, execv will not return.  */
1756           if (envp)
1757             execve (startp, argv, envp);
1758           else
1759             execv (startp, argv);
1760           
1761           if (errno == ENOEXEC)
1762             script_execute (startp, argv, envp);
1763
1764           switch (errno)
1765             {
1766             case EACCES:
1767               /* Record the we got a `Permission denied' error.  If we end
1768                * up finding no executable we can use, we want to diagnose
1769                * that we did find one but were denied access.
1770                */
1771               got_eacces = TRUE;
1772
1773               /* FALL THRU */
1774               
1775             case ENOENT:
1776 #ifdef ESTALE
1777             case ESTALE:
1778 #endif
1779 #ifdef ENOTDIR
1780             case ENOTDIR:
1781 #endif
1782               /* Those errors indicate the file is missing or not executable
1783                * by us, in which case we want to just try the next path
1784                * directory.
1785                */
1786               break;
1787
1788             case ENODEV:
1789             case ETIMEDOUT:
1790               /* Some strange filesystems like AFS return even
1791                * stranger error numbers.  They cannot reasonably mean anything
1792                * else so ignore those, too.
1793                */
1794               break;
1795
1796             default:
1797               /* Some other error means we found an executable file, but
1798                * something went wrong executing it; return the error to our
1799                * caller.
1800                */
1801               g_free (freeme);
1802               return -1;
1803             }
1804         }
1805       while (*p++ != '\0');
1806
1807       /* We tried every element and none of them worked.  */
1808       if (got_eacces)
1809         /* At least one failure was due to permissions, so report that
1810          * error.
1811          */
1812         errno = EACCES;
1813
1814       g_free (freeme);
1815     }
1816
1817   /* Return the error from the last attempt (probably ENOENT).  */
1818   return -1;
1819 }
1820
1821 /**
1822  * g_spawn_close_pid:
1823  * @pid: The process reference to close
1824  *
1825  * On some platforms, notably Windows, the #GPid type represents a resource
1826  * which must be closed to prevent resource leaking. g_spawn_close_pid()
1827  * is provided for this purpose. It should be used on all platforms, even
1828  * though it doesn't do anything under UNIX.
1829  **/
1830 void
1831 g_spawn_close_pid (GPid pid)
1832 {
1833 }