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