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