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