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