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