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