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