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