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