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