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