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