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