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