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