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