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