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