Revert "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
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 make_pipe            (gint                  p[2],
73                                       GError              **error);
74 static gboolean fork_exec_with_pipes (gboolean              intermediate_child,
75                                       const gchar          *working_directory,
76                                       gchar               **argv,
77                                       gchar               **envp,
78                                       gboolean              close_descriptors,
79                                       gboolean              search_path,
80                                       gboolean              search_path_from_envp,
81                                       gboolean              stdout_to_null,
82                                       gboolean              stderr_to_null,
83                                       gboolean              child_inherits_stdin,
84                                       gboolean              file_and_argv_zero,
85                                       GSpawnChildSetupFunc  child_setup,
86                                       gpointer              user_data,
87                                       GPid                 *child_pid,
88                                       gint                 *standard_input,
89                                       gint                 *standard_output,
90                                       gint                 *standard_error,
91                                       GError              **error);
92
93 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
94 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
95
96 /**
97  * g_spawn_async:
98  * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
99  * @argv: (array zero-terminated=1): child's argument vector
100  * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
101  * @flags: flags from #GSpawnFlags
102  * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
103  * @user_data: (closure): user data for @child_setup
104  * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
105  * @error: return location for error
106  * 
107  * See g_spawn_async_with_pipes() for a full description; this function
108  * simply calls the g_spawn_async_with_pipes() without any pipes.
109  *
110  * You should call g_spawn_close_pid() on the returned child process
111  * reference when you don't need it any more.
112  * 
113  * <note><para>
114  * If you are writing a GTK+ application, and the program you 
115  * are spawning is a graphical application, too, then you may
116  * want to use gdk_spawn_on_screen() instead to ensure that
117  * the spawned program opens its windows on the right screen.
118  * </para></note>
119  *
120  * <note><para> Note that the returned @child_pid on Windows is a
121  * handle to the child process and not its identifier. Process handles
122  * and process identifiers are different concepts on Windows.
123  * </para></note>
124  *
125  * Return value: %TRUE on success, %FALSE if error is set
126  **/
127 gboolean
128 g_spawn_async (const gchar          *working_directory,
129                gchar               **argv,
130                gchar               **envp,
131                GSpawnFlags           flags,
132                GSpawnChildSetupFunc  child_setup,
133                gpointer              user_data,
134                GPid                 *child_pid,
135                GError              **error)
136 {
137   g_return_val_if_fail (argv != NULL, FALSE);
138   
139   return g_spawn_async_with_pipes (working_directory,
140                                    argv, envp,
141                                    flags,
142                                    child_setup,
143                                    user_data,
144                                    child_pid,
145                                    NULL, NULL, NULL,
146                                    error);
147 }
148
149 /* Avoids a danger in threaded situations (calling close()
150  * on a file descriptor twice, and another thread has
151  * re-opened it since the first close)
152  */
153 static gint
154 close_and_invalidate (gint *fd)
155 {
156   gint ret;
157
158   if (*fd < 0)
159     return -1;
160   else
161     {
162     again:
163       ret = close (*fd);
164       if (ret == -1 && errno == EINTR)
165         goto again;
166       *fd = -1;
167     }
168
169   return ret;
170 }
171
172 /* Some versions of OS X define READ_OK in public headers */
173 #undef READ_OK
174
175 typedef enum
176 {
177   READ_FAILED = 0, /* FALSE */
178   READ_OK,
179   READ_EOF
180 } ReadResult;
181
182 static ReadResult
183 read_data (GString *str,
184            gint     fd,
185            GError **error)
186 {
187   gssize bytes;
188   gchar buf[4096];
189
190  again:
191   bytes = read (fd, buf, 4096);
192
193   if (bytes == 0)
194     return READ_EOF;
195   else if (bytes > 0)
196     {
197       g_string_append_len (str, buf, bytes);
198       return READ_OK;
199     }
200   else if (errno == EINTR)
201     goto again;
202   else
203     {
204       int errsv = errno;
205
206       g_set_error (error,
207                    G_SPAWN_ERROR,
208                    G_SPAWN_ERROR_READ,
209                    _("Failed to read data from child process (%s)"),
210                    g_strerror (errsv));
211
212       return READ_FAILED;
213     }
214 }
215
216 typedef struct {
217   GMainLoop *loop;
218   gint *status_p;
219 } SyncWaitpidData;
220
221 static void
222 on_sync_waitpid (GPid     pid,
223                  gint     status,
224                  gpointer user_data)
225 {
226   SyncWaitpidData *data = user_data;
227   *(data->status_p) = status;
228   g_main_loop_quit (data->loop);
229 }
230
231 /**
232  * g_spawn_sync:
233  * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
234  * @argv: (array zero-terminated=1): child's argument vector
235  * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
236  * @flags: flags from #GSpawnFlags
237  * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
238  * @user_data: (closure): user data for @child_setup
239  * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
240  * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
241  * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
242  * @error: return location for error, or %NULL
243  *
244  * Executes a child synchronously (waits for the child to exit before returning).
245  * All output from the child is stored in @standard_output and @standard_error,
246  * if those parameters are non-%NULL. Note that you must set the  
247  * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
248  * passing %NULL for @standard_output and @standard_error.
249  *
250  * If @exit_status is non-%NULL, the platform-specific exit status of
251  * the child is stored there; see the doucumentation of
252  * g_spawn_check_exit_status() for how to use and interpret this.
253  * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
254  * @flags.
255  *
256  * If an error occurs, no data is returned in @standard_output,
257  * @standard_error, or @exit_status.
258  *
259  * This function calls g_spawn_async_with_pipes() internally; see that
260  * function for full details on the other parameters and details on
261  * how these functions work on Windows.
262  * 
263  * Return value: %TRUE on success, %FALSE if an error was set.
264  **/
265 gboolean
266 g_spawn_sync (const gchar          *working_directory,
267               gchar               **argv,
268               gchar               **envp,
269               GSpawnFlags           flags,
270               GSpawnChildSetupFunc  child_setup,
271               gpointer              user_data,
272               gchar               **standard_output,
273               gchar               **standard_error,
274               gint                 *exit_status,
275               GError              **error)     
276 {
277   gint outpipe = -1;
278   gint errpipe = -1;
279   GPid pid;
280   fd_set fds;
281   gint ret;
282   GString *outstr = NULL;
283   GString *errstr = NULL;
284   gboolean failed;
285   gint status;
286   SyncWaitpidData waitpid_data;
287   
288   g_return_val_if_fail (argv != NULL, FALSE);
289   g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
290   g_return_val_if_fail (standard_output == NULL ||
291                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
292   g_return_val_if_fail (standard_error == NULL ||
293                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
294   
295   /* Just to ensure segfaults if callers try to use
296    * these when an error is reported.
297    */
298   if (standard_output)
299     *standard_output = NULL;
300
301   if (standard_error)
302     *standard_error = NULL;
303   
304   if (!fork_exec_with_pipes (FALSE,
305                              working_directory,
306                              argv,
307                              envp,
308                              !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
309                              (flags & G_SPAWN_SEARCH_PATH) != 0,
310                              (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
311                              (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
312                              (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
313                              (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
314                              (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 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                                child_setup,
683                                user_data,
684                                child_pid,
685                                standard_input,
686                                standard_output,
687                                standard_error,
688                                error);
689 }
690
691 /**
692  * g_spawn_command_line_sync:
693  * @command_line: a command line 
694  * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
695  * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
696  * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
697  * @error: return location for errors
698  *
699  * A simple version of g_spawn_sync() with little-used parameters
700  * removed, taking a command line instead of an argument vector.  See
701  * g_spawn_sync() for full details. @command_line will be parsed by
702  * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
703  * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
704  * implications, so consider using g_spawn_sync() directly if
705  * appropriate. Possible errors are those from g_spawn_sync() and those
706  * from g_shell_parse_argv().
707  *
708  * If @exit_status is non-%NULL, the platform-specific exit status of
709  * the child is stored there; see the documentation of
710  * g_spawn_check_exit_status() for how to use and interpret this.
711  * 
712  * On Windows, please note the implications of g_shell_parse_argv()
713  * parsing @command_line. Parsing is done according to Unix shell rules, not 
714  * Windows command interpreter rules.
715  * Space is a separator, and backslashes are
716  * special. Thus you cannot simply pass a @command_line containing
717  * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
718  * the backslashes will be eaten, and the space will act as a
719  * separator. You need to enclose such paths with single quotes, like
720  * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
721  *
722  * Return value: %TRUE on success, %FALSE if an error was set
723  **/
724 gboolean
725 g_spawn_command_line_sync (const gchar  *command_line,
726                            gchar       **standard_output,
727                            gchar       **standard_error,
728                            gint         *exit_status,
729                            GError      **error)
730 {
731   gboolean retval;
732   gchar **argv = NULL;
733
734   g_return_val_if_fail (command_line != NULL, FALSE);
735   
736   if (!g_shell_parse_argv (command_line,
737                            NULL, &argv,
738                            error))
739     return FALSE;
740   
741   retval = g_spawn_sync (NULL,
742                          argv,
743                          NULL,
744                          G_SPAWN_SEARCH_PATH,
745                          NULL,
746                          NULL,
747                          standard_output,
748                          standard_error,
749                          exit_status,
750                          error);
751   g_strfreev (argv);
752
753   return retval;
754 }
755
756 /**
757  * g_spawn_command_line_async:
758  * @command_line: a command line
759  * @error: return location for errors
760  * 
761  * A simple version of g_spawn_async() that parses a command line with
762  * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
763  * command line in the background. Unlike g_spawn_async(), the
764  * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
765  * that %G_SPAWN_SEARCH_PATH can have security implications, so
766  * consider using g_spawn_async() directly if appropriate. Possible
767  * errors are those from g_shell_parse_argv() and g_spawn_async().
768  * 
769  * The same concerns on Windows apply as for g_spawn_command_line_sync().
770  *
771  * Return value: %TRUE on success, %FALSE if error is set.
772  **/
773 gboolean
774 g_spawn_command_line_async (const gchar *command_line,
775                             GError     **error)
776 {
777   gboolean retval;
778   gchar **argv = NULL;
779
780   g_return_val_if_fail (command_line != NULL, FALSE);
781
782   if (!g_shell_parse_argv (command_line,
783                            NULL, &argv,
784                            error))
785     return FALSE;
786   
787   retval = g_spawn_async (NULL,
788                           argv,
789                           NULL,
790                           G_SPAWN_SEARCH_PATH,
791                           NULL,
792                           NULL,
793                           NULL,
794                           error);
795   g_strfreev (argv);
796
797   return retval;
798 }
799
800 /**
801  * g_spawn_check_exit_status:
802  * @exit_status: An exit code as returned from g_spawn_sync()
803  * @error: a #GError
804  *
805  * Set @error if @exit_status indicates the child exited abnormally
806  * (e.g. with a nonzero exit code, or via a fatal signal).
807  *
808  * The g_spawn_sync() and g_child_watch_add() family of APIs return an
809  * exit status for subprocesses encoded in a platform-specific way.
810  * On Unix, this is guaranteed to be in the same format
811  * <literal>waitpid(2)</literal> returns, and on Windows it is
812  * guaranteed to be the result of
813  * <literal>GetExitCodeProcess()</literal>.  Prior to the introduction
814  * of this function in GLib 2.34, interpreting @exit_status required
815  * use of platform-specific APIs, which is problematic for software
816  * using GLib as a cross-platform layer.
817  *
818  * Additionally, many programs simply want to determine whether or not
819  * the child exited successfully, and either propagate a #GError or
820  * print a message to standard error.  In that common case, this
821  * function can be used.  Note that the error message in @error will
822  * contain human-readable information about the exit status.
823  *
824  * The <literal>domain</literal> and <literal>code</literal> of @error
825  * have special semantics in the case where the process has an "exit
826  * code", as opposed to being killed by a signal.  On Unix, this
827  * happens if <literal>WIFEXITED</literal> would be true of
828  * @exit_status.  On Windows, it is always the case.
829  *
830  * The special semantics are that the actual exit code will be the
831  * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
832  * This allows you to differentiate between different exit codes.
833  *
834  * If the process was terminated by some means other than an exit
835  * status, the domain will be %G_SPAWN_ERROR, and the code will be
836  * %G_SPAWN_ERROR_FAILED.
837  *
838  * This function just offers convenience; you can of course also check
839  * the available platform via a macro such as %G_OS_UNIX, and use
840  * <literal>WIFEXITED()</literal> and <literal>WEXITSTATUS()</literal>
841  * on @exit_status directly.  Do not attempt to scan or parse the
842  * error message string; it may be translated and/or change in future
843  * versions of GLib.
844  *
845  * Returns: %TRUE if child exited successfully, %FALSE otherwise (and @error will be set)
846  * Since: 2.34
847  */
848 gboolean
849 g_spawn_check_exit_status (gint      exit_status,
850                            GError  **error)
851 {
852   gboolean ret = FALSE;
853
854   if (WIFEXITED (exit_status))
855     {
856       if (WEXITSTATUS (exit_status) != 0)
857         {
858           g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
859                        _("Child process exited with code %ld"),
860                        (long) WEXITSTATUS (exit_status));
861           goto out;
862         }
863     }
864   else if (WIFSIGNALED (exit_status))
865     {
866       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
867                    _("Child process killed by signal %ld"),
868                    (long) WTERMSIG (exit_status));
869       goto out;
870     }
871   else if (WIFSTOPPED (exit_status))
872     {
873       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
874                    _("Child process stopped by signal %ld"),
875                    (long) WSTOPSIG (exit_status));
876       goto out;
877     }
878   else
879     {
880       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
881                    _("Child process exited abnormally"));
882       goto out;
883     }
884
885   ret = TRUE;
886  out:
887   return ret;
888 }
889
890 static gint
891 exec_err_to_g_error (gint en)
892 {
893   switch (en)
894     {
895 #ifdef EACCES
896     case EACCES:
897       return G_SPAWN_ERROR_ACCES;
898       break;
899 #endif
900
901 #ifdef EPERM
902     case EPERM:
903       return G_SPAWN_ERROR_PERM;
904       break;
905 #endif
906
907 #ifdef E2BIG
908     case E2BIG:
909       return G_SPAWN_ERROR_TOO_BIG;
910       break;
911 #endif
912
913 #ifdef ENOEXEC
914     case ENOEXEC:
915       return G_SPAWN_ERROR_NOEXEC;
916       break;
917 #endif
918
919 #ifdef ENAMETOOLONG
920     case ENAMETOOLONG:
921       return G_SPAWN_ERROR_NAMETOOLONG;
922       break;
923 #endif
924
925 #ifdef ENOENT
926     case ENOENT:
927       return G_SPAWN_ERROR_NOENT;
928       break;
929 #endif
930
931 #ifdef ENOMEM
932     case ENOMEM:
933       return G_SPAWN_ERROR_NOMEM;
934       break;
935 #endif
936
937 #ifdef ENOTDIR
938     case ENOTDIR:
939       return G_SPAWN_ERROR_NOTDIR;
940       break;
941 #endif
942
943 #ifdef ELOOP
944     case ELOOP:
945       return G_SPAWN_ERROR_LOOP;
946       break;
947 #endif
948       
949 #ifdef ETXTBUSY
950     case ETXTBUSY:
951       return G_SPAWN_ERROR_TXTBUSY;
952       break;
953 #endif
954
955 #ifdef EIO
956     case EIO:
957       return G_SPAWN_ERROR_IO;
958       break;
959 #endif
960
961 #ifdef ENFILE
962     case ENFILE:
963       return G_SPAWN_ERROR_NFILE;
964       break;
965 #endif
966
967 #ifdef EMFILE
968     case EMFILE:
969       return G_SPAWN_ERROR_MFILE;
970       break;
971 #endif
972
973 #ifdef EINVAL
974     case EINVAL:
975       return G_SPAWN_ERROR_INVAL;
976       break;
977 #endif
978
979 #ifdef EISDIR
980     case EISDIR:
981       return G_SPAWN_ERROR_ISDIR;
982       break;
983 #endif
984
985 #ifdef ELIBBAD
986     case ELIBBAD:
987       return G_SPAWN_ERROR_LIBBAD;
988       break;
989 #endif
990       
991     default:
992       return G_SPAWN_ERROR_FAILED;
993       break;
994     }
995 }
996
997 static gssize
998 write_all (gint fd, gconstpointer vbuf, gsize to_write)
999 {
1000   gchar *buf = (gchar *) vbuf;
1001   
1002   while (to_write > 0)
1003     {
1004       gssize count = write (fd, buf, to_write);
1005       if (count < 0)
1006         {
1007           if (errno != EINTR)
1008             return FALSE;
1009         }
1010       else
1011         {
1012           to_write -= count;
1013           buf += count;
1014         }
1015     }
1016   
1017   return TRUE;
1018 }
1019
1020 G_GNUC_NORETURN
1021 static void
1022 write_err_and_exit (gint fd, gint msg)
1023 {
1024   gint en = errno;
1025   
1026   write_all (fd, &msg, sizeof(msg));
1027   write_all (fd, &en, sizeof(en));
1028   
1029   _exit (1);
1030 }
1031
1032 static int
1033 set_cloexec (void *data, gint fd)
1034 {
1035   if (fd >= GPOINTER_TO_INT (data))
1036     fcntl (fd, F_SETFD, FD_CLOEXEC);
1037
1038   return 0;
1039 }
1040
1041 #ifndef HAVE_FDWALK
1042 static int
1043 fdwalk (int (*cb)(void *data, int fd), void *data)
1044 {
1045   gint open_max;
1046   gint fd;
1047   gint res = 0;
1048   
1049 #ifdef HAVE_SYS_RESOURCE_H
1050   struct rlimit rl;
1051 #endif
1052
1053 #ifdef __linux__  
1054   DIR *d;
1055
1056   if ((d = opendir("/proc/self/fd"))) {
1057       struct dirent *de;
1058
1059       while ((de = readdir(d))) {
1060           glong l;
1061           gchar *e = NULL;
1062
1063           if (de->d_name[0] == '.')
1064               continue;
1065             
1066           errno = 0;
1067           l = strtol(de->d_name, &e, 10);
1068           if (errno != 0 || !e || *e)
1069               continue;
1070
1071           fd = (gint) l;
1072
1073           if ((glong) fd != l)
1074               continue;
1075
1076           if (fd == dirfd(d))
1077               continue;
1078
1079           if ((res = cb (data, fd)) != 0)
1080               break;
1081         }
1082       
1083       closedir(d);
1084       return res;
1085   }
1086
1087   /* If /proc is not mounted or not accessible we fall back to the old
1088    * rlimit trick */
1089
1090 #endif
1091   
1092 #ifdef HAVE_SYS_RESOURCE_H
1093       
1094   if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1095       open_max = rl.rlim_max;
1096   else
1097 #endif
1098       open_max = sysconf (_SC_OPEN_MAX);
1099
1100   for (fd = 0; fd < open_max; fd++)
1101       if ((res = cb (data, fd)) != 0)
1102           break;
1103
1104   return res;
1105 }
1106 #endif
1107
1108 static gint
1109 sane_dup2 (gint fd1, gint fd2)
1110 {
1111   gint ret;
1112
1113  retry:
1114   ret = dup2 (fd1, fd2);
1115   if (ret < 0 && errno == EINTR)
1116     goto retry;
1117
1118   return ret;
1119 }
1120
1121 static gint
1122 sane_open (const char *path, gint mode)
1123 {
1124   gint ret;
1125
1126  retry:
1127   ret = open (path, mode);
1128   if (ret < 0 && errno == EINTR)
1129     goto retry;
1130
1131   return ret;
1132 }
1133
1134 enum
1135 {
1136   CHILD_CHDIR_FAILED,
1137   CHILD_EXEC_FAILED,
1138   CHILD_DUP2_FAILED,
1139   CHILD_FORK_FAILED
1140 };
1141
1142 static void
1143 do_exec (gint                  child_err_report_fd,
1144          gint                  stdin_fd,
1145          gint                  stdout_fd,
1146          gint                  stderr_fd,
1147          const gchar          *working_directory,
1148          gchar               **argv,
1149          gchar               **envp,
1150          gboolean              close_descriptors,
1151          gboolean              search_path,
1152          gboolean              search_path_from_envp,
1153          gboolean              stdout_to_null,
1154          gboolean              stderr_to_null,
1155          gboolean              child_inherits_stdin,
1156          gboolean              file_and_argv_zero,
1157          GSpawnChildSetupFunc  child_setup,
1158          gpointer              user_data)
1159 {
1160   if (working_directory && chdir (working_directory) < 0)
1161     write_err_and_exit (child_err_report_fd,
1162                         CHILD_CHDIR_FAILED);
1163
1164   /* Close all file descriptors but stdin stdout and stderr as
1165    * soon as we exec. Note that this includes
1166    * child_err_report_fd, which keeps the parent from blocking
1167    * forever on the other end of that pipe.
1168    */
1169   if (close_descriptors)
1170     {
1171       fdwalk (set_cloexec, GINT_TO_POINTER(3));
1172     }
1173   else
1174     {
1175       /* We need to do child_err_report_fd anyway */
1176       set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1177     }
1178   
1179   /* Redirect pipes as required */
1180   
1181   if (stdin_fd >= 0)
1182     {
1183       /* dup2 can't actually fail here I don't think */
1184           
1185       if (sane_dup2 (stdin_fd, 0) < 0)
1186         write_err_and_exit (child_err_report_fd,
1187                             CHILD_DUP2_FAILED);
1188
1189       /* ignore this if it doesn't work */
1190       close_and_invalidate (&stdin_fd);
1191     }
1192   else if (!child_inherits_stdin)
1193     {
1194       /* Keep process from blocking on a read of stdin */
1195       gint read_null = open ("/dev/null", O_RDONLY);
1196       g_assert (read_null != -1);
1197       sane_dup2 (read_null, 0);
1198       close_and_invalidate (&read_null);
1199     }
1200
1201   if (stdout_fd >= 0)
1202     {
1203       /* dup2 can't actually fail here I don't think */
1204           
1205       if (sane_dup2 (stdout_fd, 1) < 0)
1206         write_err_and_exit (child_err_report_fd,
1207                             CHILD_DUP2_FAILED);
1208
1209       /* ignore this if it doesn't work */
1210       close_and_invalidate (&stdout_fd);
1211     }
1212   else if (stdout_to_null)
1213     {
1214       gint write_null = sane_open ("/dev/null", O_WRONLY);
1215       g_assert (write_null != -1);
1216       sane_dup2 (write_null, 1);
1217       close_and_invalidate (&write_null);
1218     }
1219
1220   if (stderr_fd >= 0)
1221     {
1222       /* dup2 can't actually fail here I don't think */
1223           
1224       if (sane_dup2 (stderr_fd, 2) < 0)
1225         write_err_and_exit (child_err_report_fd,
1226                             CHILD_DUP2_FAILED);
1227
1228       /* ignore this if it doesn't work */
1229       close_and_invalidate (&stderr_fd);
1230     }
1231   else if (stderr_to_null)
1232     {
1233       gint write_null = sane_open ("/dev/null", O_WRONLY);
1234       sane_dup2 (write_null, 2);
1235       close_and_invalidate (&write_null);
1236     }
1237   
1238   /* Call user function just before we exec */
1239   if (child_setup)
1240     {
1241       (* child_setup) (user_data);
1242     }
1243
1244   g_execute (argv[0],
1245              file_and_argv_zero ? argv + 1 : argv,
1246              envp, search_path, search_path_from_envp);
1247
1248   /* Exec failed */
1249   write_err_and_exit (child_err_report_fd,
1250                       CHILD_EXEC_FAILED);
1251 }
1252
1253 static gboolean
1254 read_ints (int      fd,
1255            gint*    buf,
1256            gint     n_ints_in_buf,    
1257            gint    *n_ints_read,      
1258            GError **error)
1259 {
1260   gsize bytes = 0;    
1261   
1262   while (TRUE)
1263     {
1264       gssize chunk;    
1265
1266       if (bytes >= sizeof(gint)*2)
1267         break; /* give up, who knows what happened, should not be
1268                 * possible.
1269                 */
1270           
1271     again:
1272       chunk = read (fd,
1273                     ((gchar*)buf) + bytes,
1274                     sizeof(gint) * n_ints_in_buf - bytes);
1275       if (chunk < 0 && errno == EINTR)
1276         goto again;
1277           
1278       if (chunk < 0)
1279         {
1280           int errsv = errno;
1281
1282           /* Some weird shit happened, bail out */
1283           g_set_error (error,
1284                        G_SPAWN_ERROR,
1285                        G_SPAWN_ERROR_FAILED,
1286                        _("Failed to read from child pipe (%s)"),
1287                        g_strerror (errsv));
1288
1289           return FALSE;
1290         }
1291       else if (chunk == 0)
1292         break; /* EOF */
1293       else /* chunk > 0 */
1294         bytes += chunk;
1295     }
1296
1297   *n_ints_read = (gint)(bytes / sizeof(gint));
1298
1299   return TRUE;
1300 }
1301
1302 static gboolean
1303 fork_exec_with_pipes (gboolean              intermediate_child,
1304                       const gchar          *working_directory,
1305                       gchar               **argv,
1306                       gchar               **envp,
1307                       gboolean              close_descriptors,
1308                       gboolean              search_path,
1309                       gboolean              search_path_from_envp,
1310                       gboolean              stdout_to_null,
1311                       gboolean              stderr_to_null,
1312                       gboolean              child_inherits_stdin,
1313                       gboolean              file_and_argv_zero,
1314                       GSpawnChildSetupFunc  child_setup,
1315                       gpointer              user_data,
1316                       GPid                 *child_pid,
1317                       gint                 *standard_input,
1318                       gint                 *standard_output,
1319                       gint                 *standard_error,
1320                       GError              **error)     
1321 {
1322   GPid pid = -1;
1323   gint stdin_pipe[2] = { -1, -1 };
1324   gint stdout_pipe[2] = { -1, -1 };
1325   gint stderr_pipe[2] = { -1, -1 };
1326   gint child_err_report_pipe[2] = { -1, -1 };
1327   gint child_pid_report_pipe[2] = { -1, -1 };
1328   gint status;
1329   
1330   if (!make_pipe (child_err_report_pipe, error))
1331     return FALSE;
1332
1333   if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1334     goto cleanup_and_fail;
1335   
1336   if (standard_input && !make_pipe (stdin_pipe, error))
1337     goto cleanup_and_fail;
1338   
1339   if (standard_output && !make_pipe (stdout_pipe, error))
1340     goto cleanup_and_fail;
1341
1342   if (standard_error && !make_pipe (stderr_pipe, error))
1343     goto cleanup_and_fail;
1344
1345   pid = fork ();
1346
1347   if (pid < 0)
1348     {
1349       int errsv = errno;
1350
1351       g_set_error (error,
1352                    G_SPAWN_ERROR,
1353                    G_SPAWN_ERROR_FORK,
1354                    _("Failed to fork (%s)"),
1355                    g_strerror (errsv));
1356
1357       goto cleanup_and_fail;
1358     }
1359   else if (pid == 0)
1360     {
1361       /* Immediate child. This may or may not be the child that
1362        * actually execs the new process.
1363        */
1364
1365       /* Reset some signal handlers that we may use */
1366       signal (SIGCHLD, SIG_DFL);
1367       signal (SIGINT, SIG_DFL);
1368       signal (SIGTERM, SIG_DFL);
1369       signal (SIGHUP, SIG_DFL);
1370       
1371       /* Be sure we crash if the parent exits
1372        * and we write to the err_report_pipe
1373        */
1374       signal (SIGPIPE, SIG_DFL);
1375
1376       /* Close the parent's end of the pipes;
1377        * not needed in the close_descriptors case,
1378        * though
1379        */
1380       close_and_invalidate (&child_err_report_pipe[0]);
1381       close_and_invalidate (&child_pid_report_pipe[0]);
1382       close_and_invalidate (&stdin_pipe[1]);
1383       close_and_invalidate (&stdout_pipe[0]);
1384       close_and_invalidate (&stderr_pipe[0]);
1385       
1386       if (intermediate_child)
1387         {
1388           /* We need to fork an intermediate child that launches the
1389            * final child. The purpose of the intermediate child
1390            * is to exit, so we can waitpid() it immediately.
1391            * Then the grandchild will not become a zombie.
1392            */
1393           GPid grandchild_pid;
1394
1395           grandchild_pid = fork ();
1396
1397           if (grandchild_pid < 0)
1398             {
1399               /* report -1 as child PID */
1400               write_all (child_pid_report_pipe[1], &grandchild_pid,
1401                          sizeof(grandchild_pid));
1402               
1403               write_err_and_exit (child_err_report_pipe[1],
1404                                   CHILD_FORK_FAILED);              
1405             }
1406           else if (grandchild_pid == 0)
1407             {
1408               do_exec (child_err_report_pipe[1],
1409                        stdin_pipe[0],
1410                        stdout_pipe[1],
1411                        stderr_pipe[1],
1412                        working_directory,
1413                        argv,
1414                        envp,
1415                        close_descriptors,
1416                        search_path,
1417                        search_path_from_envp,
1418                        stdout_to_null,
1419                        stderr_to_null,
1420                        child_inherits_stdin,
1421                        file_and_argv_zero,
1422                        child_setup,
1423                        user_data);
1424             }
1425           else
1426             {
1427               write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1428               close_and_invalidate (&child_pid_report_pipe[1]);
1429               
1430               _exit (0);
1431             }
1432         }
1433       else
1434         {
1435           /* Just run the child.
1436            */
1437
1438           do_exec (child_err_report_pipe[1],
1439                    stdin_pipe[0],
1440                    stdout_pipe[1],
1441                    stderr_pipe[1],
1442                    working_directory,
1443                    argv,
1444                    envp,
1445                    close_descriptors,
1446                    search_path,
1447                    search_path_from_envp,
1448                    stdout_to_null,
1449                    stderr_to_null,
1450                    child_inherits_stdin,
1451                    file_and_argv_zero,
1452                    child_setup,
1453                    user_data);
1454         }
1455     }
1456   else
1457     {
1458       /* Parent */
1459       
1460       gint buf[2];
1461       gint n_ints = 0;    
1462
1463       /* Close the uncared-about ends of the pipes */
1464       close_and_invalidate (&child_err_report_pipe[1]);
1465       close_and_invalidate (&child_pid_report_pipe[1]);
1466       close_and_invalidate (&stdin_pipe[0]);
1467       close_and_invalidate (&stdout_pipe[1]);
1468       close_and_invalidate (&stderr_pipe[1]);
1469
1470       /* If we had an intermediate child, reap it */
1471       if (intermediate_child)
1472         {
1473         wait_again:
1474           if (waitpid (pid, &status, 0) < 0)
1475             {
1476               if (errno == EINTR)
1477                 goto wait_again;
1478               else if (errno == ECHILD)
1479                 ; /* do nothing, child already reaped */
1480               else
1481                 g_warning ("waitpid() should not fail in "
1482                            "'fork_exec_with_pipes'");
1483             }
1484         }
1485       
1486
1487       if (!read_ints (child_err_report_pipe[0],
1488                       buf, 2, &n_ints,
1489                       error))
1490         goto cleanup_and_fail;
1491         
1492       if (n_ints >= 2)
1493         {
1494           /* Error from the child. */
1495
1496           switch (buf[0])
1497             {
1498             case CHILD_CHDIR_FAILED:
1499               g_set_error (error,
1500                            G_SPAWN_ERROR,
1501                            G_SPAWN_ERROR_CHDIR,
1502                            _("Failed to change to directory '%s' (%s)"),
1503                            working_directory,
1504                            g_strerror (buf[1]));
1505
1506               break;
1507               
1508             case CHILD_EXEC_FAILED:
1509               g_set_error (error,
1510                            G_SPAWN_ERROR,
1511                            exec_err_to_g_error (buf[1]),
1512                            _("Failed to execute child process \"%s\" (%s)"),
1513                            argv[0],
1514                            g_strerror (buf[1]));
1515
1516               break;
1517               
1518             case CHILD_DUP2_FAILED:
1519               g_set_error (error,
1520                            G_SPAWN_ERROR,
1521                            G_SPAWN_ERROR_FAILED,
1522                            _("Failed to redirect output or input of child process (%s)"),
1523                            g_strerror (buf[1]));
1524
1525               break;
1526
1527             case CHILD_FORK_FAILED:
1528               g_set_error (error,
1529                            G_SPAWN_ERROR,
1530                            G_SPAWN_ERROR_FORK,
1531                            _("Failed to fork child process (%s)"),
1532                            g_strerror (buf[1]));
1533               break;
1534               
1535             default:
1536               g_set_error (error,
1537                            G_SPAWN_ERROR,
1538                            G_SPAWN_ERROR_FAILED,
1539                            _("Unknown error executing child process \"%s\""),
1540                            argv[0]);
1541               break;
1542             }
1543
1544           goto cleanup_and_fail;
1545         }
1546
1547       /* Get child pid from intermediate child pipe. */
1548       if (intermediate_child)
1549         {
1550           n_ints = 0;
1551           
1552           if (!read_ints (child_pid_report_pipe[0],
1553                           buf, 1, &n_ints, error))
1554             goto cleanup_and_fail;
1555
1556           if (n_ints < 1)
1557             {
1558               int errsv = errno;
1559
1560               g_set_error (error,
1561                            G_SPAWN_ERROR,
1562                            G_SPAWN_ERROR_FAILED,
1563                            _("Failed to read enough data from child pid pipe (%s)"),
1564                            g_strerror (errsv));
1565               goto cleanup_and_fail;
1566             }
1567           else
1568             {
1569               /* we have the child pid */
1570               pid = buf[0];
1571             }
1572         }
1573       
1574       /* Success against all odds! return the information */
1575       close_and_invalidate (&child_err_report_pipe[0]);
1576       close_and_invalidate (&child_pid_report_pipe[0]);
1577  
1578       if (child_pid)
1579         *child_pid = pid;
1580
1581       if (standard_input)
1582         *standard_input = stdin_pipe[1];
1583       if (standard_output)
1584         *standard_output = stdout_pipe[0];
1585       if (standard_error)
1586         *standard_error = stderr_pipe[0];
1587       
1588       return TRUE;
1589     }
1590
1591  cleanup_and_fail:
1592
1593   /* There was an error from the Child, reap the child to avoid it being
1594      a zombie.
1595    */
1596
1597   if (pid > 0)
1598   {
1599     wait_failed:
1600      if (waitpid (pid, NULL, 0) < 0)
1601        {
1602           if (errno == EINTR)
1603             goto wait_failed;
1604           else if (errno == ECHILD)
1605             ; /* do nothing, child already reaped */
1606           else
1607             g_warning ("waitpid() should not fail in "
1608                        "'fork_exec_with_pipes'");
1609        }
1610    }
1611
1612   close_and_invalidate (&child_err_report_pipe[0]);
1613   close_and_invalidate (&child_err_report_pipe[1]);
1614   close_and_invalidate (&child_pid_report_pipe[0]);
1615   close_and_invalidate (&child_pid_report_pipe[1]);
1616   close_and_invalidate (&stdin_pipe[0]);
1617   close_and_invalidate (&stdin_pipe[1]);
1618   close_and_invalidate (&stdout_pipe[0]);
1619   close_and_invalidate (&stdout_pipe[1]);
1620   close_and_invalidate (&stderr_pipe[0]);
1621   close_and_invalidate (&stderr_pipe[1]);
1622
1623   return FALSE;
1624 }
1625
1626 static gboolean
1627 make_pipe (gint     p[2],
1628            GError **error)
1629 {
1630   if (pipe (p) < 0)
1631     {
1632       gint errsv = errno;
1633       g_set_error (error,
1634                    G_SPAWN_ERROR,
1635                    G_SPAWN_ERROR_FAILED,
1636                    _("Failed to create pipe for communicating with child process (%s)"),
1637                    g_strerror (errsv));
1638       return FALSE;
1639     }
1640   else
1641     return TRUE;
1642 }
1643
1644 /* Based on execvp from GNU C Library */
1645
1646 static void
1647 script_execute (const gchar *file,
1648                 gchar      **argv,
1649                 gchar      **envp)
1650 {
1651   /* Count the arguments.  */
1652   int argc = 0;
1653   while (argv[argc])
1654     ++argc;
1655   
1656   /* Construct an argument list for the shell.  */
1657   {
1658     gchar **new_argv;
1659
1660     new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1661     
1662     new_argv[0] = (char *) "/bin/sh";
1663     new_argv[1] = (char *) file;
1664     while (argc > 0)
1665       {
1666         new_argv[argc + 1] = argv[argc];
1667         --argc;
1668       }
1669
1670     /* Execute the shell. */
1671     if (envp)
1672       execve (new_argv[0], new_argv, envp);
1673     else
1674       execv (new_argv[0], new_argv);
1675     
1676     g_free (new_argv);
1677   }
1678 }
1679
1680 static gchar*
1681 my_strchrnul (const gchar *str, gchar c)
1682 {
1683   gchar *p = (gchar*) str;
1684   while (*p && (*p != c))
1685     ++p;
1686
1687   return p;
1688 }
1689
1690 static gint
1691 g_execute (const gchar *file,
1692            gchar      **argv,
1693            gchar      **envp,
1694            gboolean     search_path,
1695            gboolean     search_path_from_envp)
1696 {
1697   if (*file == '\0')
1698     {
1699       /* We check the simple case first. */
1700       errno = ENOENT;
1701       return -1;
1702     }
1703
1704   if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1705     {
1706       /* Don't search when it contains a slash. */
1707       if (envp)
1708         execve (file, argv, envp);
1709       else
1710         execv (file, argv);
1711       
1712       if (errno == ENOEXEC)
1713         script_execute (file, argv, envp);
1714     }
1715   else
1716     {
1717       gboolean got_eacces = 0;
1718       const gchar *path, *p;
1719       gchar *name, *freeme;
1720       gsize len;
1721       gsize pathlen;
1722
1723       path = NULL;
1724       if (search_path_from_envp)
1725         path = g_environ_getenv (envp, "PATH");
1726       if (search_path && path == NULL)
1727         path = g_getenv ("PATH");
1728
1729       if (path == NULL)
1730         {
1731           /* There is no `PATH' in the environment.  The default
1732            * search path in libc is the current directory followed by
1733            * the path `confstr' returns for `_CS_PATH'.
1734            */
1735
1736           /* In GLib we put . last, for security, and don't use the
1737            * unportable confstr(); UNIX98 does not actually specify
1738            * what to search if PATH is unset. POSIX may, dunno.
1739            */
1740           
1741           path = "/bin:/usr/bin:.";
1742         }
1743
1744       len = strlen (file) + 1;
1745       pathlen = strlen (path);
1746       freeme = name = g_malloc (pathlen + len + 1);
1747       
1748       /* Copy the file name at the top, including '\0'  */
1749       memcpy (name + pathlen + 1, file, len);
1750       name = name + pathlen;
1751       /* And add the slash before the filename  */
1752       *name = '/';
1753
1754       p = path;
1755       do
1756         {
1757           char *startp;
1758
1759           path = p;
1760           p = my_strchrnul (path, ':');
1761
1762           if (p == path)
1763             /* Two adjacent colons, or a colon at the beginning or the end
1764              * of `PATH' means to search the current directory.
1765              */
1766             startp = name + 1;
1767           else
1768             startp = memcpy (name - (p - path), path, p - path);
1769
1770           /* Try to execute this name.  If it works, execv will not return.  */
1771           if (envp)
1772             execve (startp, argv, envp);
1773           else
1774             execv (startp, argv);
1775           
1776           if (errno == ENOEXEC)
1777             script_execute (startp, argv, envp);
1778
1779           switch (errno)
1780             {
1781             case EACCES:
1782               /* Record the we got a `Permission denied' error.  If we end
1783                * up finding no executable we can use, we want to diagnose
1784                * that we did find one but were denied access.
1785                */
1786               got_eacces = TRUE;
1787
1788               /* FALL THRU */
1789               
1790             case ENOENT:
1791 #ifdef ESTALE
1792             case ESTALE:
1793 #endif
1794 #ifdef ENOTDIR
1795             case ENOTDIR:
1796 #endif
1797               /* Those errors indicate the file is missing or not executable
1798                * by us, in which case we want to just try the next path
1799                * directory.
1800                */
1801               break;
1802
1803             case ENODEV:
1804             case ETIMEDOUT:
1805               /* Some strange filesystems like AFS return even
1806                * stranger error numbers.  They cannot reasonably mean anything
1807                * else so ignore those, too.
1808                */
1809               break;
1810
1811             default:
1812               /* Some other error means we found an executable file, but
1813                * something went wrong executing it; return the error to our
1814                * caller.
1815                */
1816               g_free (freeme);
1817               return -1;
1818             }
1819         }
1820       while (*p++ != '\0');
1821
1822       /* We tried every element and none of them worked.  */
1823       if (got_eacces)
1824         /* At least one failure was due to permissions, so report that
1825          * error.
1826          */
1827         errno = EACCES;
1828
1829       g_free (freeme);
1830     }
1831
1832   /* Return the error from the last attempt (probably ENOENT).  */
1833   return -1;
1834 }
1835
1836 /**
1837  * g_spawn_close_pid:
1838  * @pid: The process reference to close
1839  *
1840  * On some platforms, notably Windows, the #GPid type represents a resource
1841  * which must be closed to prevent resource leaking. g_spawn_close_pid()
1842  * is provided for this purpose. It should be used on all platforms, even
1843  * though it doesn't do anything under UNIX.
1844  **/
1845 void
1846 g_spawn_close_pid (GPid pid)
1847 {
1848 }