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