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