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