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