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