1 /* gspawn.c - Process launching
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.
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.
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.
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.
26 #include <sys/types.h>
33 #include <stdlib.h> /* for fdwalk */
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
50 #include "gstrfuncs.h"
51 #include "gtestutils.h"
58 * @Short_description: process launching
59 * @Title: Spawning Processes
64 static gint g_execute (const gchar *file,
67 gboolean search_path);
69 static gboolean make_pipe (gint p[2],
71 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
72 const gchar *working_directory,
75 gboolean close_descriptors,
77 gboolean stdout_to_null,
78 gboolean stderr_to_null,
79 gboolean child_inherits_stdin,
80 gboolean file_and_argv_zero,
81 GSpawnChildSetupFunc child_setup,
85 gint *standard_output,
90 g_spawn_error_quark (void)
92 return g_quark_from_static_string ("g-exec-error-quark");
97 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
98 * @argv: (array zero-terminated=1): child's argument vector
99 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
100 * @flags: flags from #GSpawnFlags
101 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
102 * @user_data: (closure): user data for @child_setup
103 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
104 * @error: return location for error
106 * See g_spawn_async_with_pipes() for a full description; this function
107 * simply calls the g_spawn_async_with_pipes() without any pipes.
109 * You should call g_spawn_close_pid() on the returned child process
110 * reference when you don't need it any more.
113 * If you are writing a GTK+ application, and the program you
114 * are spawning is a graphical application, too, then you may
115 * want to use gdk_spawn_on_screen() instead to ensure that
116 * the spawned program opens its windows on the right screen.
119 * <note><para> Note that the returned @child_pid on Windows is a
120 * handle to the child process and not its identifier. Process handles
121 * and process identifiers are different concepts on Windows.
124 * Return value: %TRUE on success, %FALSE if error is set
127 g_spawn_async (const gchar *working_directory,
131 GSpawnChildSetupFunc child_setup,
136 g_return_val_if_fail (argv != NULL, FALSE);
138 return g_spawn_async_with_pipes (working_directory,
148 /* Avoids a danger in threaded situations (calling close()
149 * on a file descriptor twice, and another thread has
150 * re-opened it since the first close)
153 close_and_invalidate (gint *fd)
163 if (ret == -1 && errno == EINTR)
171 /* Some versions of OS X define READ_OK in public headers */
176 READ_FAILED = 0, /* FALSE */
182 read_data (GString *str,
190 bytes = read (fd, buf, 4096);
196 g_string_append_len (str, buf, bytes);
199 else if (errno == EINTR)
208 _("Failed to read data from child process (%s)"),
217 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
218 * @argv: (array zero-terminated=1): child's argument vector
219 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
220 * @flags: flags from #GSpawnFlags
221 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
222 * @user_data: (closure): user data for @child_setup
223 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
224 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
225 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
226 * @error: return location for error, or %NULL
228 * Executes a child synchronously (waits for the child to exit before returning).
229 * All output from the child is stored in @standard_output and @standard_error,
230 * if those parameters are non-%NULL. Note that you must set the
231 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
232 * passing %NULL for @standard_output and @standard_error.
233 * If @exit_status is non-%NULL, the exit status of the child is stored
234 * there as it would be returned by waitpid(); standard UNIX macros such
235 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
236 * Note that this function call waitpid() even if @exit_status is %NULL, and
237 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
238 * If an error occurs, no data is returned in @standard_output,
239 * @standard_error, or @exit_status.
241 * This function calls g_spawn_async_with_pipes() internally; see that
242 * function for full details on the other parameters and details on
243 * how these functions work on Windows.
245 * Return value: %TRUE on success, %FALSE if an error was set.
248 g_spawn_sync (const gchar *working_directory,
252 GSpawnChildSetupFunc child_setup,
254 gchar **standard_output,
255 gchar **standard_error,
264 GString *outstr = NULL;
265 GString *errstr = NULL;
269 g_return_val_if_fail (argv != NULL, FALSE);
270 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
271 g_return_val_if_fail (standard_output == NULL ||
272 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
273 g_return_val_if_fail (standard_error == NULL ||
274 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
276 /* Just to ensure segfaults if callers try to use
277 * these when an error is reported.
280 *standard_output = NULL;
283 *standard_error = NULL;
285 if (!fork_exec_with_pipes (FALSE,
289 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
290 (flags & G_SPAWN_SEARCH_PATH) != 0,
291 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
292 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
293 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
294 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
299 standard_output ? &outpipe : NULL,
300 standard_error ? &errpipe : NULL,
304 /* Read data from child. */
310 outstr = g_string_new (NULL);
315 errstr = g_string_new (NULL);
318 /* Read data until we get EOF on both pipes. */
327 FD_SET (outpipe, &fds);
329 FD_SET (errpipe, &fds);
331 ret = select (MAX (outpipe, errpipe) + 1,
334 NULL /* no timeout */);
348 _("Unexpected error in select() reading data from a child process (%s)"),
354 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
356 switch (read_data (outstr, outpipe, error))
362 close_and_invalidate (&outpipe);
373 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
375 switch (read_data (errstr, errpipe, error))
381 close_and_invalidate (&errpipe);
393 /* These should only be open still if we had an error. */
396 close_and_invalidate (&outpipe);
398 close_and_invalidate (&errpipe);
400 /* Wait for child to exit, even if we have
405 ret = waitpid (pid, &status, 0);
411 else if (errno == ECHILD)
415 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.");
419 /* We don't need the exit status. */
424 if (!failed) /* avoid error pileups */
433 _("Unexpected error in waitpid() (%s)"),
442 g_string_free (outstr, TRUE);
444 g_string_free (errstr, TRUE);
451 *exit_status = status;
454 *standard_output = g_string_free (outstr, FALSE);
457 *standard_error = g_string_free (errstr, FALSE);
464 * g_spawn_async_with_pipes:
465 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
466 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
467 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
468 * @flags: flags from #GSpawnFlags
469 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
470 * @user_data: (closure): user data for @child_setup
471 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
472 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
473 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
474 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
475 * @error: return location for error
477 * Executes a child program asynchronously (your program will not
478 * block waiting for the child to exit). The child program is
479 * specified by the only argument that must be provided, @argv. @argv
480 * should be a %NULL-terminated array of strings, to be passed as the
481 * argument vector for the child. The first string in @argv is of
482 * course the name of the program to execute. By default, the name of
483 * the program must be a full path; the <envar>PATH</envar> shell variable
484 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
485 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
486 * used, then the program will be run from the current directory (or
487 * @working_directory, if specified); this might be unexpected or even
488 * dangerous in some cases when the current directory is world-writable.
490 * On Windows, note that all the string or string vector arguments to
491 * this function and the other g_spawn*() functions are in UTF-8, the
492 * GLib file name encoding. Unicode characters that are not part of
493 * the system codepage passed in these arguments will be correctly
494 * available in the spawned program only if it uses wide character API
495 * to retrieve its command line. For C programs built with Microsoft's
496 * tools it is enough to make the program have a wmain() instead of
497 * main(). wmain() has a wide character argument vector as parameter.
499 * At least currently, mingw doesn't support wmain(), so if you use
500 * mingw to develop the spawned program, it will have to call the
501 * undocumented function __wgetmainargs() to get the wide character
502 * argument vector and environment. See gspawn-win32-helper.c in the
503 * GLib sources or init.c in the mingw runtime sources for a prototype
504 * for that function. Alternatively, you can retrieve the Win32 system
505 * level wide character command line passed to the spawned program
506 * using the GetCommandLineW() function.
508 * On Windows the low-level child process creation API
509 * <function>CreateProcess()</function> doesn't use argument vectors,
510 * but a command line. The C runtime library's
511 * <function>spawn*()</function> family of functions (which
512 * g_spawn_async_with_pipes() eventually calls) paste the argument
513 * vector elements together into a command line, and the C runtime startup code
514 * does a corresponding reconstruction of an argument vector from the
515 * command line, to be passed to main(). Complications arise when you have
516 * argument vector elements that contain spaces of double quotes. The
517 * <function>spawn*()</function> functions don't do any quoting or
518 * escaping, but on the other hand the startup code does do unquoting
519 * and unescaping in order to enable receiving arguments with embedded
520 * spaces or double quotes. To work around this asymmetry,
521 * g_spawn_async_with_pipes() will do quoting and escaping on argument
522 * vector elements that need it before calling the C runtime
525 * The returned @child_pid on Windows is a handle to the child
526 * process, not its identifier. Process handles and process
527 * identifiers are different concepts on Windows.
529 * @envp is a %NULL-terminated array of strings, where each string
530 * has the form <literal>KEY=VALUE</literal>. This will become
531 * the child's environment. If @envp is %NULL, the child inherits its
532 * parent's environment.
534 * @flags should be the bitwise OR of any flags you want to affect the
535 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
536 * child will not automatically be reaped; you must use a child watch to
537 * be notified about the death of the child process. Eventually you must
538 * call g_spawn_close_pid() on the @child_pid, in order to free
539 * resources which may be associated with the child process. (On Unix,
540 * using a child watch is equivalent to calling waitpid() or handling
541 * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
542 * is equivalent to calling CloseHandle() on the process handle returned
543 * in @child_pid). See g_child_watch_add().
545 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
546 * descriptors will be inherited by the child; otherwise all
547 * descriptors except stdin/stdout/stderr will be closed before
548 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
549 * means that <literal>argv[0]</literal> need not be an absolute path, it
550 * will be looked for in the user's <envar>PATH</envar>.
551 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
552 * be discarded, instead of going to the same location as the parent's
553 * standard output. If you use this flag, @standard_output must be %NULL.
554 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
555 * will be discarded, instead of going to the same location as the parent's
556 * standard error. If you use this flag, @standard_error must be %NULL.
557 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
558 * standard input (by default, the child's standard input is attached to
559 * /dev/null). If you use this flag, @standard_input must be %NULL.
560 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
561 * the file to execute, while the remaining elements are the
562 * actual argument vector to pass to the file. Normally
563 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
564 * passes all of @argv to the child.
566 * @child_setup and @user_data are a function and user data. On POSIX
567 * platforms, the function is called in the child after GLib has
568 * performed all the setup it plans to perform (including creating
569 * pipes, closing file descriptors, etc.) but before calling
570 * exec(). That is, @child_setup is called just
571 * before calling exec() in the child. Obviously
572 * actions taken in this function will only affect the child, not the
575 * On Windows, there is no separate fork() and exec()
576 * functionality. Child processes are created and run with a single
577 * API call, CreateProcess(). There is no sensible thing @child_setup
578 * could be used for on Windows so it is ignored and not called.
580 * If non-%NULL, @child_pid will on Unix be filled with the child's
581 * process ID. You can use the process ID to send signals to the
582 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
583 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
584 * filled with a handle to the child process only if you specified the
585 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
586 * process using the Win32 API, for example wait for its termination
587 * with the <function>WaitFor*()</function> functions, or examine its
588 * exit code with GetExitCodeProcess(). You should close the handle
589 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
591 * If non-%NULL, the @standard_input, @standard_output, @standard_error
592 * locations will be filled with file descriptors for writing to the child's
593 * standard input or reading from its standard output or standard error.
594 * The caller of g_spawn_async_with_pipes() must close these file descriptors
595 * when they are no longer in use. If these parameters are %NULL, the corresponding
596 * pipe won't be created.
598 * If @standard_input is NULL, the child's standard input is attached to
599 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
601 * If @standard_error is NULL, the child's standard error goes to the same
602 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
605 * If @standard_output is NULL, the child's standard output goes to the same
606 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
609 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
610 * If an error is set, the function returns %FALSE. Errors
611 * are reported even if they occur in the child (for example if the
612 * executable in <literal>argv[0]</literal> is not found). Typically
613 * the <literal>message</literal> field of returned errors should be displayed
614 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
616 * If an error occurs, @child_pid, @standard_input, @standard_output,
617 * and @standard_error will not be filled with valid values.
619 * If @child_pid is not %NULL and an error does not occur then the returned
620 * process reference must be closed using g_spawn_close_pid().
623 * If you are writing a GTK+ application, and the program you
624 * are spawning is a graphical application, too, then you may
625 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
626 * the spawned program opens its windows on the right screen.
629 * Return value: %TRUE on success, %FALSE if an error was set
632 g_spawn_async_with_pipes (const gchar *working_directory,
636 GSpawnChildSetupFunc child_setup,
639 gint *standard_input,
640 gint *standard_output,
641 gint *standard_error,
644 g_return_val_if_fail (argv != NULL, FALSE);
645 g_return_val_if_fail (standard_output == NULL ||
646 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
647 g_return_val_if_fail (standard_error == NULL ||
648 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
649 /* can't inherit stdin if we have an input pipe. */
650 g_return_val_if_fail (standard_input == NULL ||
651 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
653 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
657 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
658 (flags & G_SPAWN_SEARCH_PATH) != 0,
659 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
660 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
661 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
662 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
673 * g_spawn_command_line_sync:
674 * @command_line: a command line
675 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
676 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
677 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
678 * @error: return location for errors
680 * A simple version of g_spawn_sync() with little-used parameters
681 * removed, taking a command line instead of an argument vector. See
682 * g_spawn_sync() for full details. @command_line will be parsed by
683 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
684 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
685 * implications, so consider using g_spawn_sync() directly if
686 * appropriate. Possible errors are those from g_spawn_sync() and those
687 * from g_shell_parse_argv().
689 * If @exit_status is non-%NULL, the exit status of the child is stored there as
690 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
691 * and WEXITSTATUS() must be used to evaluate the exit status.
693 * On Windows, please note the implications of g_shell_parse_argv()
694 * parsing @command_line. Parsing is done according to Unix shell rules, not
695 * Windows command interpreter rules.
696 * Space is a separator, and backslashes are
697 * special. Thus you cannot simply pass a @command_line containing
698 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
699 * the backslashes will be eaten, and the space will act as a
700 * separator. You need to enclose such paths with single quotes, like
701 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
703 * Return value: %TRUE on success, %FALSE if an error was set
706 g_spawn_command_line_sync (const gchar *command_line,
707 gchar **standard_output,
708 gchar **standard_error,
715 g_return_val_if_fail (command_line != NULL, FALSE);
717 if (!g_shell_parse_argv (command_line,
722 retval = g_spawn_sync (NULL,
738 * g_spawn_command_line_async:
739 * @command_line: a command line
740 * @error: return location for errors
742 * A simple version of g_spawn_async() that parses a command line with
743 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
744 * command line in the background. Unlike g_spawn_async(), the
745 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
746 * that %G_SPAWN_SEARCH_PATH can have security implications, so
747 * consider using g_spawn_async() directly if appropriate. Possible
748 * errors are those from g_shell_parse_argv() and g_spawn_async().
750 * The same concerns on Windows apply as for g_spawn_command_line_sync().
752 * Return value: %TRUE on success, %FALSE if error is set.
755 g_spawn_command_line_async (const gchar *command_line,
761 g_return_val_if_fail (command_line != NULL, FALSE);
763 if (!g_shell_parse_argv (command_line,
768 retval = g_spawn_async (NULL,
782 exec_err_to_g_error (gint en)
788 return G_SPAWN_ERROR_ACCES;
794 return G_SPAWN_ERROR_PERM;
800 return G_SPAWN_ERROR_TOO_BIG;
806 return G_SPAWN_ERROR_NOEXEC;
812 return G_SPAWN_ERROR_NAMETOOLONG;
818 return G_SPAWN_ERROR_NOENT;
824 return G_SPAWN_ERROR_NOMEM;
830 return G_SPAWN_ERROR_NOTDIR;
836 return G_SPAWN_ERROR_LOOP;
842 return G_SPAWN_ERROR_TXTBUSY;
848 return G_SPAWN_ERROR_IO;
854 return G_SPAWN_ERROR_NFILE;
860 return G_SPAWN_ERROR_MFILE;
866 return G_SPAWN_ERROR_INVAL;
872 return G_SPAWN_ERROR_ISDIR;
878 return G_SPAWN_ERROR_LIBBAD;
883 return G_SPAWN_ERROR_FAILED;
889 write_all (gint fd, gconstpointer vbuf, gsize to_write)
891 gchar *buf = (gchar *) vbuf;
895 gssize count = write (fd, buf, to_write);
913 write_err_and_exit (gint fd, gint msg)
917 write_all (fd, &msg, sizeof(msg));
918 write_all (fd, &en, sizeof(en));
924 set_cloexec (void *data, gint fd)
926 if (fd >= GPOINTER_TO_INT (data))
927 fcntl (fd, F_SETFD, FD_CLOEXEC);
934 fdwalk (int (*cb)(void *data, int fd), void *data)
940 #ifdef HAVE_SYS_RESOURCE_H
947 if ((d = opendir("/proc/self/fd"))) {
950 while ((de = readdir(d))) {
954 if (de->d_name[0] == '.')
958 l = strtol(de->d_name, &e, 10);
959 if (errno != 0 || !e || *e)
970 if ((res = cb (data, fd)) != 0)
978 /* If /proc is not mounted or not accessible we fall back to the old
983 #ifdef HAVE_SYS_RESOURCE_H
985 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
986 open_max = rl.rlim_max;
989 open_max = sysconf (_SC_OPEN_MAX);
991 for (fd = 0; fd < open_max; fd++)
992 if ((res = cb (data, fd)) != 0)
1000 sane_dup2 (gint fd1, gint fd2)
1005 ret = dup2 (fd1, fd2);
1006 if (ret < 0 && errno == EINTR)
1013 sane_open (const char *path, gint mode)
1018 ret = open (path, mode);
1019 if (ret < 0 && errno == EINTR)
1034 do_exec (gint child_err_report_fd,
1038 const gchar *working_directory,
1041 gboolean close_descriptors,
1042 gboolean search_path,
1043 gboolean stdout_to_null,
1044 gboolean stderr_to_null,
1045 gboolean child_inherits_stdin,
1046 gboolean file_and_argv_zero,
1047 GSpawnChildSetupFunc child_setup,
1050 if (working_directory && chdir (working_directory) < 0)
1051 write_err_and_exit (child_err_report_fd,
1052 CHILD_CHDIR_FAILED);
1054 /* Close all file descriptors but stdin stdout and stderr as
1055 * soon as we exec. Note that this includes
1056 * child_err_report_fd, which keeps the parent from blocking
1057 * forever on the other end of that pipe.
1059 if (close_descriptors)
1061 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1065 /* We need to do child_err_report_fd anyway */
1066 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1069 /* Redirect pipes as required */
1073 /* dup2 can't actually fail here I don't think */
1075 if (sane_dup2 (stdin_fd, 0) < 0)
1076 write_err_and_exit (child_err_report_fd,
1079 /* ignore this if it doesn't work */
1080 close_and_invalidate (&stdin_fd);
1082 else if (!child_inherits_stdin)
1084 /* Keep process from blocking on a read of stdin */
1085 gint read_null = open ("/dev/null", O_RDONLY);
1086 sane_dup2 (read_null, 0);
1087 close_and_invalidate (&read_null);
1092 /* dup2 can't actually fail here I don't think */
1094 if (sane_dup2 (stdout_fd, 1) < 0)
1095 write_err_and_exit (child_err_report_fd,
1098 /* ignore this if it doesn't work */
1099 close_and_invalidate (&stdout_fd);
1101 else if (stdout_to_null)
1103 gint write_null = sane_open ("/dev/null", O_WRONLY);
1104 sane_dup2 (write_null, 1);
1105 close_and_invalidate (&write_null);
1110 /* dup2 can't actually fail here I don't think */
1112 if (sane_dup2 (stderr_fd, 2) < 0)
1113 write_err_and_exit (child_err_report_fd,
1116 /* ignore this if it doesn't work */
1117 close_and_invalidate (&stderr_fd);
1119 else if (stderr_to_null)
1121 gint write_null = sane_open ("/dev/null", O_WRONLY);
1122 sane_dup2 (write_null, 2);
1123 close_and_invalidate (&write_null);
1126 /* Call user function just before we exec */
1129 (* child_setup) (user_data);
1133 file_and_argv_zero ? argv + 1 : argv,
1137 write_err_and_exit (child_err_report_fd,
1154 if (bytes >= sizeof(gint)*2)
1155 break; /* give up, who knows what happened, should not be
1161 ((gchar*)buf) + bytes,
1162 sizeof(gint) * n_ints_in_buf - bytes);
1163 if (chunk < 0 && errno == EINTR)
1170 /* Some weird shit happened, bail out */
1173 G_SPAWN_ERROR_FAILED,
1174 _("Failed to read from child pipe (%s)"),
1175 g_strerror (errsv));
1179 else if (chunk == 0)
1181 else /* chunk > 0 */
1185 *n_ints_read = (gint)(bytes / sizeof(gint));
1191 fork_exec_with_pipes (gboolean intermediate_child,
1192 const gchar *working_directory,
1195 gboolean close_descriptors,
1196 gboolean search_path,
1197 gboolean stdout_to_null,
1198 gboolean stderr_to_null,
1199 gboolean child_inherits_stdin,
1200 gboolean file_and_argv_zero,
1201 GSpawnChildSetupFunc child_setup,
1204 gint *standard_input,
1205 gint *standard_output,
1206 gint *standard_error,
1210 gint stdin_pipe[2] = { -1, -1 };
1211 gint stdout_pipe[2] = { -1, -1 };
1212 gint stderr_pipe[2] = { -1, -1 };
1213 gint child_err_report_pipe[2] = { -1, -1 };
1214 gint child_pid_report_pipe[2] = { -1, -1 };
1217 if (!make_pipe (child_err_report_pipe, error))
1220 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1221 goto cleanup_and_fail;
1223 if (standard_input && !make_pipe (stdin_pipe, error))
1224 goto cleanup_and_fail;
1226 if (standard_output && !make_pipe (stdout_pipe, error))
1227 goto cleanup_and_fail;
1229 if (standard_error && !make_pipe (stderr_pipe, error))
1230 goto cleanup_and_fail;
1241 _("Failed to fork (%s)"),
1242 g_strerror (errsv));
1244 goto cleanup_and_fail;
1248 /* Immediate child. This may or may not be the child that
1249 * actually execs the new process.
1252 /* Reset some signal handlers that we may use */
1253 signal (SIGCHLD, SIG_DFL);
1254 signal (SIGINT, SIG_DFL);
1255 signal (SIGTERM, SIG_DFL);
1256 signal (SIGHUP, SIG_DFL);
1258 /* Be sure we crash if the parent exits
1259 * and we write to the err_report_pipe
1261 signal (SIGPIPE, SIG_DFL);
1263 /* Close the parent's end of the pipes;
1264 * not needed in the close_descriptors case,
1267 close_and_invalidate (&child_err_report_pipe[0]);
1268 close_and_invalidate (&child_pid_report_pipe[0]);
1269 close_and_invalidate (&stdin_pipe[1]);
1270 close_and_invalidate (&stdout_pipe[0]);
1271 close_and_invalidate (&stderr_pipe[0]);
1273 if (intermediate_child)
1275 /* We need to fork an intermediate child that launches the
1276 * final child. The purpose of the intermediate child
1277 * is to exit, so we can waitpid() it immediately.
1278 * Then the grandchild will not become a zombie.
1280 GPid grandchild_pid;
1282 grandchild_pid = fork ();
1284 if (grandchild_pid < 0)
1286 /* report -1 as child PID */
1287 write_all (child_pid_report_pipe[1], &grandchild_pid,
1288 sizeof(grandchild_pid));
1290 write_err_and_exit (child_err_report_pipe[1],
1293 else if (grandchild_pid == 0)
1295 do_exec (child_err_report_pipe[1],
1306 child_inherits_stdin,
1313 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1314 close_and_invalidate (&child_pid_report_pipe[1]);
1321 /* Just run the child.
1324 do_exec (child_err_report_pipe[1],
1335 child_inherits_stdin,
1348 /* Close the uncared-about ends of the pipes */
1349 close_and_invalidate (&child_err_report_pipe[1]);
1350 close_and_invalidate (&child_pid_report_pipe[1]);
1351 close_and_invalidate (&stdin_pipe[0]);
1352 close_and_invalidate (&stdout_pipe[1]);
1353 close_and_invalidate (&stderr_pipe[1]);
1355 /* If we had an intermediate child, reap it */
1356 if (intermediate_child)
1359 if (waitpid (pid, &status, 0) < 0)
1363 else if (errno == ECHILD)
1364 ; /* do nothing, child already reaped */
1366 g_warning ("waitpid() should not fail in "
1367 "'fork_exec_with_pipes'");
1372 if (!read_ints (child_err_report_pipe[0],
1375 goto cleanup_and_fail;
1379 /* Error from the child. */
1383 case CHILD_CHDIR_FAILED:
1386 G_SPAWN_ERROR_CHDIR,
1387 _("Failed to change to directory '%s' (%s)"),
1389 g_strerror (buf[1]));
1393 case CHILD_EXEC_FAILED:
1396 exec_err_to_g_error (buf[1]),
1397 _("Failed to execute child process \"%s\" (%s)"),
1399 g_strerror (buf[1]));
1403 case CHILD_DUP2_FAILED:
1406 G_SPAWN_ERROR_FAILED,
1407 _("Failed to redirect output or input of child process (%s)"),
1408 g_strerror (buf[1]));
1412 case CHILD_FORK_FAILED:
1416 _("Failed to fork child process (%s)"),
1417 g_strerror (buf[1]));
1423 G_SPAWN_ERROR_FAILED,
1424 _("Unknown error executing child process \"%s\""),
1429 goto cleanup_and_fail;
1432 /* Get child pid from intermediate child pipe. */
1433 if (intermediate_child)
1437 if (!read_ints (child_pid_report_pipe[0],
1438 buf, 1, &n_ints, error))
1439 goto cleanup_and_fail;
1447 G_SPAWN_ERROR_FAILED,
1448 _("Failed to read enough data from child pid pipe (%s)"),
1449 g_strerror (errsv));
1450 goto cleanup_and_fail;
1454 /* we have the child pid */
1459 /* Success against all odds! return the information */
1460 close_and_invalidate (&child_err_report_pipe[0]);
1461 close_and_invalidate (&child_pid_report_pipe[0]);
1467 *standard_input = stdin_pipe[1];
1468 if (standard_output)
1469 *standard_output = stdout_pipe[0];
1471 *standard_error = stderr_pipe[0];
1478 /* There was an error from the Child, reap the child to avoid it being
1485 if (waitpid (pid, NULL, 0) < 0)
1489 else if (errno == ECHILD)
1490 ; /* do nothing, child already reaped */
1492 g_warning ("waitpid() should not fail in "
1493 "'fork_exec_with_pipes'");
1497 close_and_invalidate (&child_err_report_pipe[0]);
1498 close_and_invalidate (&child_err_report_pipe[1]);
1499 close_and_invalidate (&child_pid_report_pipe[0]);
1500 close_and_invalidate (&child_pid_report_pipe[1]);
1501 close_and_invalidate (&stdin_pipe[0]);
1502 close_and_invalidate (&stdin_pipe[1]);
1503 close_and_invalidate (&stdout_pipe[0]);
1504 close_and_invalidate (&stdout_pipe[1]);
1505 close_and_invalidate (&stderr_pipe[0]);
1506 close_and_invalidate (&stderr_pipe[1]);
1512 make_pipe (gint p[2],
1520 G_SPAWN_ERROR_FAILED,
1521 _("Failed to create pipe for communicating with child process (%s)"),
1522 g_strerror (errsv));
1529 /* Based on execvp from GNU C Library */
1532 script_execute (const gchar *file,
1535 gboolean search_path)
1537 /* Count the arguments. */
1542 /* Construct an argument list for the shell. */
1546 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1548 new_argv[0] = (char *) "/bin/sh";
1549 new_argv[1] = (char *) file;
1552 new_argv[argc + 1] = argv[argc];
1556 /* Execute the shell. */
1558 execve (new_argv[0], new_argv, envp);
1560 execv (new_argv[0], new_argv);
1567 my_strchrnul (const gchar *str, gchar c)
1569 gchar *p = (gchar*) str;
1570 while (*p && (*p != c))
1577 g_execute (const gchar *file,
1580 gboolean search_path)
1584 /* We check the simple case first. */
1589 if (!search_path || strchr (file, '/') != NULL)
1591 /* Don't search when it contains a slash. */
1593 execve (file, argv, envp);
1597 if (errno == ENOEXEC)
1598 script_execute (file, argv, envp, FALSE);
1602 gboolean got_eacces = 0;
1603 const gchar *path, *p;
1604 gchar *name, *freeme;
1608 path = g_getenv ("PATH");
1611 /* There is no `PATH' in the environment. The default
1612 * search path in libc is the current directory followed by
1613 * the path `confstr' returns for `_CS_PATH'.
1616 /* In GLib we put . last, for security, and don't use the
1617 * unportable confstr(); UNIX98 does not actually specify
1618 * what to search if PATH is unset. POSIX may, dunno.
1621 path = "/bin:/usr/bin:.";
1624 len = strlen (file) + 1;
1625 pathlen = strlen (path);
1626 freeme = name = g_malloc (pathlen + len + 1);
1628 /* Copy the file name at the top, including '\0' */
1629 memcpy (name + pathlen + 1, file, len);
1630 name = name + pathlen;
1631 /* And add the slash before the filename */
1640 p = my_strchrnul (path, ':');
1643 /* Two adjacent colons, or a colon at the beginning or the end
1644 * of `PATH' means to search the current directory.
1648 startp = memcpy (name - (p - path), path, p - path);
1650 /* Try to execute this name. If it works, execv will not return. */
1652 execve (startp, argv, envp);
1654 execv (startp, argv);
1656 if (errno == ENOEXEC)
1657 script_execute (startp, argv, envp, search_path);
1662 /* Record the we got a `Permission denied' error. If we end
1663 * up finding no executable we can use, we want to diagnose
1664 * that we did find one but were denied access.
1677 /* Those errors indicate the file is missing or not executable
1678 * by us, in which case we want to just try the next path
1684 /* Some other error means we found an executable file, but
1685 * something went wrong executing it; return the error to our
1692 while (*p++ != '\0');
1694 /* We tried every element and none of them worked. */
1696 /* At least one failure was due to permissions, so report that
1704 /* Return the error from the last attempt (probably ENOENT). */
1709 * g_spawn_close_pid:
1710 * @pid: The process reference to close
1712 * On some platforms, notably Windows, the #GPid type represents a resource
1713 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1714 * is provided for this purpose. It should be used on all platforms, even
1715 * though it doesn't do anything under UNIX.
1718 g_spawn_close_pid (GPid pid)