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 */
49 #include "gstrfuncs.h"
50 #include "gtestutils.h"
54 static gint g_execute (const gchar *file,
57 gboolean search_path);
59 static gboolean make_pipe (gint p[2],
61 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
62 const gchar *working_directory,
65 gboolean close_descriptors,
67 gboolean stdout_to_null,
68 gboolean stderr_to_null,
69 gboolean child_inherits_stdin,
70 gboolean file_and_argv_zero,
71 GSpawnChildSetupFunc child_setup,
75 gint *standard_output,
80 g_spawn_error_quark (void)
82 return g_quark_from_static_string ("g-exec-error-quark");
87 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
88 * @argv: (array zero-terminated=1): child's argument vector
89 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
90 * @flags: flags from #GSpawnFlags
91 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
92 * @user_data: (closure): user data for @child_setup
93 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
94 * @error: return location for error
96 * See g_spawn_async_with_pipes() for a full description; this function
97 * simply calls the g_spawn_async_with_pipes() without any pipes.
99 * You should call g_spawn_close_pid() on the returned child process
100 * reference when you don't need it any more.
103 * If you are writing a GTK+ application, and the program you
104 * are spawning is a graphical application, too, then you may
105 * want to use gdk_spawn_on_screen() instead to ensure that
106 * the spawned program opens its windows on the right screen.
109 * <note><para> Note that the returned @child_pid on Windows is a
110 * handle to the child process and not its identifier. Process handles
111 * and process identifiers are different concepts on Windows.
114 * Return value: %TRUE on success, %FALSE if error is set
117 g_spawn_async (const gchar *working_directory,
121 GSpawnChildSetupFunc child_setup,
126 g_return_val_if_fail (argv != NULL, FALSE);
128 return g_spawn_async_with_pipes (working_directory,
138 /* Avoids a danger in threaded situations (calling close()
139 * on a file descriptor twice, and another thread has
140 * re-opened it since the first close)
143 close_and_invalidate (gint *fd)
153 if (ret == -1 && errno == EINTR)
161 /* Some versions of OS X define READ_OK in public headers */
166 READ_FAILED = 0, /* FALSE */
172 read_data (GString *str,
181 bytes = read (fd, buf, 4096);
187 g_string_append_len (str, buf, bytes);
190 else if (bytes < 0 && errno == EINTR)
199 _("Failed to read data from child process (%s)"),
210 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
211 * @argv: (array zero-terminated=1): child's argument vector
212 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
213 * @flags: flags from #GSpawnFlags
214 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
215 * @user_data: (closure): user data for @child_setup
216 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
217 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
218 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
219 * @error: return location for error, or %NULL
221 * Executes a child synchronously (waits for the child to exit before returning).
222 * All output from the child is stored in @standard_output and @standard_error,
223 * if those parameters are non-%NULL. Note that you must set the
224 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
225 * passing %NULL for @standard_output and @standard_error.
226 * If @exit_status is non-%NULL, the exit status of the child is stored
227 * there as it would be returned by waitpid(); standard UNIX macros such
228 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
229 * Note that this function call waitpid() even if @exit_status is %NULL, and
230 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
231 * If an error occurs, no data is returned in @standard_output,
232 * @standard_error, or @exit_status.
234 * This function calls g_spawn_async_with_pipes() internally; see that
235 * function for full details on the other parameters and details on
236 * how these functions work on Windows.
238 * Return value: %TRUE on success, %FALSE if an error was set.
241 g_spawn_sync (const gchar *working_directory,
245 GSpawnChildSetupFunc child_setup,
247 gchar **standard_output,
248 gchar **standard_error,
257 GString *outstr = NULL;
258 GString *errstr = NULL;
262 g_return_val_if_fail (argv != NULL, FALSE);
263 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
264 g_return_val_if_fail (standard_output == NULL ||
265 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
266 g_return_val_if_fail (standard_error == NULL ||
267 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
269 /* Just to ensure segfaults if callers try to use
270 * these when an error is reported.
273 *standard_output = NULL;
276 *standard_error = NULL;
278 if (!fork_exec_with_pipes (FALSE,
282 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
283 (flags & G_SPAWN_SEARCH_PATH) != 0,
284 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
285 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
286 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
287 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
292 standard_output ? &outpipe : NULL,
293 standard_error ? &errpipe : NULL,
297 /* Read data from child. */
303 outstr = g_string_new (NULL);
308 errstr = g_string_new (NULL);
311 /* Read data until we get EOF on both pipes. */
320 FD_SET (outpipe, &fds);
322 FD_SET (errpipe, &fds);
324 ret = select (MAX (outpipe, errpipe) + 1,
327 NULL /* no timeout */);
341 _("Unexpected error in select() reading data from a child process (%s)"),
347 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
349 switch (read_data (outstr, outpipe, error))
355 close_and_invalidate (&outpipe);
366 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
368 switch (read_data (errstr, errpipe, error))
374 close_and_invalidate (&errpipe);
386 /* These should only be open still if we had an error. */
389 close_and_invalidate (&outpipe);
391 close_and_invalidate (&errpipe);
393 /* Wait for child to exit, even if we have
398 ret = waitpid (pid, &status, 0);
404 else if (errno == ECHILD)
408 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.");
412 /* We don't need the exit status. */
417 if (!failed) /* avoid error pileups */
426 _("Unexpected error in waitpid() (%s)"),
435 g_string_free (outstr, TRUE);
437 g_string_free (errstr, TRUE);
444 *exit_status = status;
447 *standard_output = g_string_free (outstr, FALSE);
450 *standard_error = g_string_free (errstr, FALSE);
457 * g_spawn_async_with_pipes:
458 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
459 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
460 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
461 * @flags: flags from #GSpawnFlags
462 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
463 * @user_data: (closure): user data for @child_setup
464 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
465 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
466 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
467 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
468 * @error: return location for error
470 * Executes a child program asynchronously (your program will not
471 * block waiting for the child to exit). The child program is
472 * specified by the only argument that must be provided, @argv. @argv
473 * should be a %NULL-terminated array of strings, to be passed as the
474 * argument vector for the child. The first string in @argv is of
475 * course the name of the program to execute. By default, the name of
476 * the program must be a full path; the <envar>PATH</envar> shell variable
477 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
479 * On Windows, note that all the string or string vector arguments to
480 * this function and the other g_spawn*() functions are in UTF-8, the
481 * GLib file name encoding. Unicode characters that are not part of
482 * the system codepage passed in these arguments will be correctly
483 * available in the spawned program only if it uses wide character API
484 * to retrieve its command line. For C programs built with Microsoft's
485 * tools it is enough to make the program have a wmain() instead of
486 * main(). wmain() has a wide character argument vector as parameter.
488 * At least currently, mingw doesn't support wmain(), so if you use
489 * mingw to develop the spawned program, it will have to call the
490 * undocumented function __wgetmainargs() to get the wide character
491 * argument vector and environment. See gspawn-win32-helper.c in the
492 * GLib sources or init.c in the mingw runtime sources for a prototype
493 * for that function. Alternatively, you can retrieve the Win32 system
494 * level wide character command line passed to the spawned program
495 * using the GetCommandLineW() function.
497 * On Windows the low-level child process creation API
498 * <function>CreateProcess()</function> doesn't use argument vectors,
499 * but a command line. The C runtime library's
500 * <function>spawn*()</function> family of functions (which
501 * g_spawn_async_with_pipes() eventually calls) paste the argument
502 * vector elements together into a command line, and the C runtime startup code
503 * does a corresponding reconstruction of an argument vector from the
504 * command line, to be passed to main(). Complications arise when you have
505 * argument vector elements that contain spaces of double quotes. The
506 * <function>spawn*()</function> functions don't do any quoting or
507 * escaping, but on the other hand the startup code does do unquoting
508 * and unescaping in order to enable receiving arguments with embedded
509 * spaces or double quotes. To work around this asymmetry,
510 * g_spawn_async_with_pipes() will do quoting and escaping on argument
511 * vector elements that need it before calling the C runtime
514 * The returned @child_pid on Windows is a handle to the child
515 * process, not its identifier. Process handles and process
516 * identifiers are different concepts on Windows.
518 * @envp is a %NULL-terminated array of strings, where each string
519 * has the form <literal>KEY=VALUE</literal>. This will become
520 * the child's environment. If @envp is %NULL, the child inherits its
521 * parent's environment.
523 * @flags should be the bitwise OR of any flags you want to affect the
524 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
525 * the child will not automatically be reaped; you must use a
526 * #GChildWatch source to be notified about the death of the child
527 * process. Eventually you must call g_spawn_close_pid() on the
528 * @child_pid, in order to free resources which may be associated
529 * with the child process. (On Unix, using a #GChildWatch source is
530 * equivalent to calling waitpid() or handling the %SIGCHLD signal
531 * manually. On Windows, calling g_spawn_close_pid() is equivalent
532 * to calling CloseHandle() on the process handle returned in
535 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
536 * descriptors will be inherited by the child; otherwise all
537 * descriptors except stdin/stdout/stderr will be closed before
538 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
539 * means that <literal>argv[0]</literal> need not be an absolute path, it
540 * will be looked for in the user's <envar>PATH</envar>.
541 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
542 * be discarded, instead of going to the same location as the parent's
543 * standard output. If you use this flag, @standard_output must be %NULL.
544 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
545 * will be discarded, instead of going to the same location as the parent's
546 * standard error. If you use this flag, @standard_error must be %NULL.
547 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
548 * standard input (by default, the child's standard input is attached to
549 * /dev/null). If you use this flag, @standard_input must be %NULL.
550 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
551 * the file to execute, while the remaining elements are the
552 * actual argument vector to pass to the file. Normally
553 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
554 * passes all of @argv to the child.
556 * @child_setup and @user_data are a function and user data. On POSIX
557 * platforms, the function is called in the child after GLib has
558 * performed all the setup it plans to perform (including creating
559 * pipes, closing file descriptors, etc.) but before calling
560 * exec(). That is, @child_setup is called just
561 * before calling exec() in the child. Obviously
562 * actions taken in this function will only affect the child, not the
565 * On Windows, there is no separate fork() and exec()
566 * functionality. Child processes are created and run with a single
567 * API call, CreateProcess(). There is no sensible thing @child_setup
568 * could be used for on Windows so it is ignored and not called.
570 * If non-%NULL, @child_pid will on Unix be filled with the child's
571 * process ID. You can use the process ID to send signals to the
572 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
573 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
574 * filled with a handle to the child process only if you specified the
575 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
576 * process using the Win32 API, for example wait for its termination
577 * with the <function>WaitFor*()</function> functions, or examine its
578 * exit code with GetExitCodeProcess(). You should close the handle
579 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
581 * If non-%NULL, the @standard_input, @standard_output, @standard_error
582 * locations will be filled with file descriptors for writing to the child's
583 * standard input or reading from its standard output or standard error.
584 * The caller of g_spawn_async_with_pipes() must close these file descriptors
585 * when they are no longer in use. If these parameters are %NULL, the corresponding
586 * pipe won't be created.
588 * If @standard_input is NULL, the child's standard input is attached to
589 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
591 * If @standard_error is NULL, the child's standard error goes to the same
592 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
595 * If @standard_output is NULL, the child's standard output goes to the same
596 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
599 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
600 * If an error is set, the function returns %FALSE. Errors
601 * are reported even if they occur in the child (for example if the
602 * executable in <literal>argv[0]</literal> is not found). Typically
603 * the <literal>message</literal> field of returned errors should be displayed
604 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
606 * If an error occurs, @child_pid, @standard_input, @standard_output,
607 * and @standard_error will not be filled with valid values.
609 * If @child_pid is not %NULL and an error does not occur then the returned
610 * process reference must be closed using g_spawn_close_pid().
613 * If you are writing a GTK+ application, and the program you
614 * are spawning is a graphical application, too, then you may
615 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
616 * the spawned program opens its windows on the right screen.
619 * Return value: %TRUE on success, %FALSE if an error was set
622 g_spawn_async_with_pipes (const gchar *working_directory,
626 GSpawnChildSetupFunc child_setup,
629 gint *standard_input,
630 gint *standard_output,
631 gint *standard_error,
634 g_return_val_if_fail (argv != NULL, FALSE);
635 g_return_val_if_fail (standard_output == NULL ||
636 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
637 g_return_val_if_fail (standard_error == NULL ||
638 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
639 /* can't inherit stdin if we have an input pipe. */
640 g_return_val_if_fail (standard_input == NULL ||
641 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
643 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
647 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
648 (flags & G_SPAWN_SEARCH_PATH) != 0,
649 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
650 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
651 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
652 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
663 * g_spawn_command_line_sync:
664 * @command_line: a command line
665 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
666 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
667 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
668 * @error: return location for errors
670 * A simple version of g_spawn_sync() with little-used parameters
671 * removed, taking a command line instead of an argument vector. See
672 * g_spawn_sync() for full details. @command_line will be parsed by
673 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
674 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
675 * implications, so consider using g_spawn_sync() directly if
676 * appropriate. Possible errors are those from g_spawn_sync() and those
677 * from g_shell_parse_argv().
679 * If @exit_status is non-%NULL, the exit status of the child is stored there as
680 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
681 * and WEXITSTATUS() must be used to evaluate the exit status.
683 * On Windows, please note the implications of g_shell_parse_argv()
684 * parsing @command_line. Parsing is done according to Unix shell rules, not
685 * Windows command interpreter rules.
686 * Space is a separator, and backslashes are
687 * special. Thus you cannot simply pass a @command_line containing
688 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
689 * the backslashes will be eaten, and the space will act as a
690 * separator. You need to enclose such paths with single quotes, like
691 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
693 * Return value: %TRUE on success, %FALSE if an error was set
696 g_spawn_command_line_sync (const gchar *command_line,
697 gchar **standard_output,
698 gchar **standard_error,
705 g_return_val_if_fail (command_line != NULL, FALSE);
707 if (!g_shell_parse_argv (command_line,
712 retval = g_spawn_sync (NULL,
728 * g_spawn_command_line_async:
729 * @command_line: a command line
730 * @error: return location for errors
732 * A simple version of g_spawn_async() that parses a command line with
733 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
734 * command line in the background. Unlike g_spawn_async(), the
735 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
736 * that %G_SPAWN_SEARCH_PATH can have security implications, so
737 * consider using g_spawn_async() directly if appropriate. Possible
738 * errors are those from g_shell_parse_argv() and g_spawn_async().
740 * The same concerns on Windows apply as for g_spawn_command_line_sync().
742 * Return value: %TRUE on success, %FALSE if error is set.
745 g_spawn_command_line_async (const gchar *command_line,
751 g_return_val_if_fail (command_line != NULL, FALSE);
753 if (!g_shell_parse_argv (command_line,
758 retval = g_spawn_async (NULL,
772 exec_err_to_g_error (gint en)
778 return G_SPAWN_ERROR_ACCES;
784 return G_SPAWN_ERROR_PERM;
790 return G_SPAWN_ERROR_2BIG;
796 return G_SPAWN_ERROR_NOEXEC;
802 return G_SPAWN_ERROR_NAMETOOLONG;
808 return G_SPAWN_ERROR_NOENT;
814 return G_SPAWN_ERROR_NOMEM;
820 return G_SPAWN_ERROR_NOTDIR;
826 return G_SPAWN_ERROR_LOOP;
832 return G_SPAWN_ERROR_TXTBUSY;
838 return G_SPAWN_ERROR_IO;
844 return G_SPAWN_ERROR_NFILE;
850 return G_SPAWN_ERROR_MFILE;
856 return G_SPAWN_ERROR_INVAL;
862 return G_SPAWN_ERROR_ISDIR;
868 return G_SPAWN_ERROR_LIBBAD;
873 return G_SPAWN_ERROR_FAILED;
879 write_all (gint fd, gconstpointer vbuf, gsize to_write)
881 gchar *buf = (gchar *) vbuf;
885 gssize count = write (fd, buf, to_write);
903 write_err_and_exit (gint fd, gint msg)
907 write_all (fd, &msg, sizeof(msg));
908 write_all (fd, &en, sizeof(en));
914 set_cloexec (void *data, gint fd)
916 if (fd >= GPOINTER_TO_INT (data))
917 fcntl (fd, F_SETFD, FD_CLOEXEC);
924 fdwalk (int (*cb)(void *data, int fd), void *data)
930 #ifdef HAVE_SYS_RESOURCE_H
937 if ((d = opendir("/proc/self/fd"))) {
940 while ((de = readdir(d))) {
944 if (de->d_name[0] == '.')
948 l = strtol(de->d_name, &e, 10);
949 if (errno != 0 || !e || *e)
960 if ((res = cb (data, fd)) != 0)
968 /* If /proc is not mounted or not accessible we fall back to the old
973 #ifdef HAVE_SYS_RESOURCE_H
975 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
976 open_max = rl.rlim_max;
979 open_max = sysconf (_SC_OPEN_MAX);
981 for (fd = 0; fd < open_max; fd++)
982 if ((res = cb (data, fd)) != 0)
990 sane_dup2 (gint fd1, gint fd2)
995 ret = dup2 (fd1, fd2);
996 if (ret < 0 && errno == EINTR)
1003 sane_open (const char *path, gint mode)
1008 ret = open (path, mode);
1009 if (ret < 0 && errno == EINTR)
1024 do_exec (gint child_err_report_fd,
1028 const gchar *working_directory,
1031 gboolean close_descriptors,
1032 gboolean search_path,
1033 gboolean stdout_to_null,
1034 gboolean stderr_to_null,
1035 gboolean child_inherits_stdin,
1036 gboolean file_and_argv_zero,
1037 GSpawnChildSetupFunc child_setup,
1040 if (working_directory && chdir (working_directory) < 0)
1041 write_err_and_exit (child_err_report_fd,
1042 CHILD_CHDIR_FAILED);
1044 /* Close all file descriptors but stdin stdout and stderr as
1045 * soon as we exec. Note that this includes
1046 * child_err_report_fd, which keeps the parent from blocking
1047 * forever on the other end of that pipe.
1049 if (close_descriptors)
1051 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1055 /* We need to do child_err_report_fd anyway */
1056 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1059 /* Redirect pipes as required */
1063 /* dup2 can't actually fail here I don't think */
1065 if (sane_dup2 (stdin_fd, 0) < 0)
1066 write_err_and_exit (child_err_report_fd,
1069 /* ignore this if it doesn't work */
1070 close_and_invalidate (&stdin_fd);
1072 else if (!child_inherits_stdin)
1074 /* Keep process from blocking on a read of stdin */
1075 gint read_null = open ("/dev/null", O_RDONLY);
1076 sane_dup2 (read_null, 0);
1077 close_and_invalidate (&read_null);
1082 /* dup2 can't actually fail here I don't think */
1084 if (sane_dup2 (stdout_fd, 1) < 0)
1085 write_err_and_exit (child_err_report_fd,
1088 /* ignore this if it doesn't work */
1089 close_and_invalidate (&stdout_fd);
1091 else if (stdout_to_null)
1093 gint write_null = sane_open ("/dev/null", O_WRONLY);
1094 sane_dup2 (write_null, 1);
1095 close_and_invalidate (&write_null);
1100 /* dup2 can't actually fail here I don't think */
1102 if (sane_dup2 (stderr_fd, 2) < 0)
1103 write_err_and_exit (child_err_report_fd,
1106 /* ignore this if it doesn't work */
1107 close_and_invalidate (&stderr_fd);
1109 else if (stderr_to_null)
1111 gint write_null = sane_open ("/dev/null", O_WRONLY);
1112 sane_dup2 (write_null, 2);
1113 close_and_invalidate (&write_null);
1116 /* Call user function just before we exec */
1119 (* child_setup) (user_data);
1123 file_and_argv_zero ? argv + 1 : argv,
1127 write_err_and_exit (child_err_report_fd,
1144 if (bytes >= sizeof(gint)*2)
1145 break; /* give up, who knows what happened, should not be
1151 ((gchar*)buf) + bytes,
1152 sizeof(gint) * n_ints_in_buf - bytes);
1153 if (chunk < 0 && errno == EINTR)
1160 /* Some weird shit happened, bail out */
1163 G_SPAWN_ERROR_FAILED,
1164 _("Failed to read from child pipe (%s)"),
1165 g_strerror (errsv));
1169 else if (chunk == 0)
1171 else /* chunk > 0 */
1175 *n_ints_read = (gint)(bytes / sizeof(gint));
1181 fork_exec_with_pipes (gboolean intermediate_child,
1182 const gchar *working_directory,
1185 gboolean close_descriptors,
1186 gboolean search_path,
1187 gboolean stdout_to_null,
1188 gboolean stderr_to_null,
1189 gboolean child_inherits_stdin,
1190 gboolean file_and_argv_zero,
1191 GSpawnChildSetupFunc child_setup,
1194 gint *standard_input,
1195 gint *standard_output,
1196 gint *standard_error,
1200 gint stdin_pipe[2] = { -1, -1 };
1201 gint stdout_pipe[2] = { -1, -1 };
1202 gint stderr_pipe[2] = { -1, -1 };
1203 gint child_err_report_pipe[2] = { -1, -1 };
1204 gint child_pid_report_pipe[2] = { -1, -1 };
1207 if (!make_pipe (child_err_report_pipe, error))
1210 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1211 goto cleanup_and_fail;
1213 if (standard_input && !make_pipe (stdin_pipe, error))
1214 goto cleanup_and_fail;
1216 if (standard_output && !make_pipe (stdout_pipe, error))
1217 goto cleanup_and_fail;
1219 if (standard_error && !make_pipe (stderr_pipe, error))
1220 goto cleanup_and_fail;
1231 _("Failed to fork (%s)"),
1232 g_strerror (errsv));
1234 goto cleanup_and_fail;
1238 /* Immediate child. This may or may not be the child that
1239 * actually execs the new process.
1242 /* Reset some signal handlers that we may use */
1243 signal (SIGCHLD, SIG_DFL);
1244 signal (SIGINT, SIG_DFL);
1245 signal (SIGTERM, SIG_DFL);
1246 signal (SIGHUP, SIG_DFL);
1248 /* Be sure we crash if the parent exits
1249 * and we write to the err_report_pipe
1251 signal (SIGPIPE, SIG_DFL);
1253 /* Close the parent's end of the pipes;
1254 * not needed in the close_descriptors case,
1257 close_and_invalidate (&child_err_report_pipe[0]);
1258 close_and_invalidate (&child_pid_report_pipe[0]);
1259 close_and_invalidate (&stdin_pipe[1]);
1260 close_and_invalidate (&stdout_pipe[0]);
1261 close_and_invalidate (&stderr_pipe[0]);
1263 if (intermediate_child)
1265 /* We need to fork an intermediate child that launches the
1266 * final child. The purpose of the intermediate child
1267 * is to exit, so we can waitpid() it immediately.
1268 * Then the grandchild will not become a zombie.
1270 GPid grandchild_pid;
1272 grandchild_pid = fork ();
1274 if (grandchild_pid < 0)
1276 /* report -1 as child PID */
1277 write_all (child_pid_report_pipe[1], &grandchild_pid,
1278 sizeof(grandchild_pid));
1280 write_err_and_exit (child_err_report_pipe[1],
1283 else if (grandchild_pid == 0)
1285 do_exec (child_err_report_pipe[1],
1296 child_inherits_stdin,
1303 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1304 close_and_invalidate (&child_pid_report_pipe[1]);
1311 /* Just run the child.
1314 do_exec (child_err_report_pipe[1],
1325 child_inherits_stdin,
1338 /* Close the uncared-about ends of the pipes */
1339 close_and_invalidate (&child_err_report_pipe[1]);
1340 close_and_invalidate (&child_pid_report_pipe[1]);
1341 close_and_invalidate (&stdin_pipe[0]);
1342 close_and_invalidate (&stdout_pipe[1]);
1343 close_and_invalidate (&stderr_pipe[1]);
1345 /* If we had an intermediate child, reap it */
1346 if (intermediate_child)
1349 if (waitpid (pid, &status, 0) < 0)
1353 else if (errno == ECHILD)
1354 ; /* do nothing, child already reaped */
1356 g_warning ("waitpid() should not fail in "
1357 "'fork_exec_with_pipes'");
1362 if (!read_ints (child_err_report_pipe[0],
1365 goto cleanup_and_fail;
1369 /* Error from the child. */
1373 case CHILD_CHDIR_FAILED:
1376 G_SPAWN_ERROR_CHDIR,
1377 _("Failed to change to directory '%s' (%s)"),
1379 g_strerror (buf[1]));
1383 case CHILD_EXEC_FAILED:
1386 exec_err_to_g_error (buf[1]),
1387 _("Failed to execute child process \"%s\" (%s)"),
1389 g_strerror (buf[1]));
1393 case CHILD_DUP2_FAILED:
1396 G_SPAWN_ERROR_FAILED,
1397 _("Failed to redirect output or input of child process (%s)"),
1398 g_strerror (buf[1]));
1402 case CHILD_FORK_FAILED:
1406 _("Failed to fork child process (%s)"),
1407 g_strerror (buf[1]));
1413 G_SPAWN_ERROR_FAILED,
1414 _("Unknown error executing child process \"%s\""),
1419 goto cleanup_and_fail;
1422 /* Get child pid from intermediate child pipe. */
1423 if (intermediate_child)
1427 if (!read_ints (child_pid_report_pipe[0],
1428 buf, 1, &n_ints, error))
1429 goto cleanup_and_fail;
1437 G_SPAWN_ERROR_FAILED,
1438 _("Failed to read enough data from child pid pipe (%s)"),
1439 g_strerror (errsv));
1440 goto cleanup_and_fail;
1444 /* we have the child pid */
1449 /* Success against all odds! return the information */
1450 close_and_invalidate (&child_err_report_pipe[0]);
1451 close_and_invalidate (&child_pid_report_pipe[0]);
1457 *standard_input = stdin_pipe[1];
1458 if (standard_output)
1459 *standard_output = stdout_pipe[0];
1461 *standard_error = stderr_pipe[0];
1468 /* There was an error from the Child, reap the child to avoid it being
1475 if (waitpid (pid, NULL, 0) < 0)
1479 else if (errno == ECHILD)
1480 ; /* do nothing, child already reaped */
1482 g_warning ("waitpid() should not fail in "
1483 "'fork_exec_with_pipes'");
1487 close_and_invalidate (&child_err_report_pipe[0]);
1488 close_and_invalidate (&child_err_report_pipe[1]);
1489 close_and_invalidate (&child_pid_report_pipe[0]);
1490 close_and_invalidate (&child_pid_report_pipe[1]);
1491 close_and_invalidate (&stdin_pipe[0]);
1492 close_and_invalidate (&stdin_pipe[1]);
1493 close_and_invalidate (&stdout_pipe[0]);
1494 close_and_invalidate (&stdout_pipe[1]);
1495 close_and_invalidate (&stderr_pipe[0]);
1496 close_and_invalidate (&stderr_pipe[1]);
1502 make_pipe (gint p[2],
1510 G_SPAWN_ERROR_FAILED,
1511 _("Failed to create pipe for communicating with child process (%s)"),
1512 g_strerror (errsv));
1519 /* Based on execvp from GNU C Library */
1522 script_execute (const gchar *file,
1525 gboolean search_path)
1527 /* Count the arguments. */
1532 /* Construct an argument list for the shell. */
1536 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1538 new_argv[0] = (char *) "/bin/sh";
1539 new_argv[1] = (char *) file;
1542 new_argv[argc + 1] = argv[argc];
1546 /* Execute the shell. */
1548 execve (new_argv[0], new_argv, envp);
1550 execv (new_argv[0], new_argv);
1557 my_strchrnul (const gchar *str, gchar c)
1559 gchar *p = (gchar*) str;
1560 while (*p && (*p != c))
1567 g_execute (const gchar *file,
1570 gboolean search_path)
1574 /* We check the simple case first. */
1579 if (!search_path || strchr (file, '/') != NULL)
1581 /* Don't search when it contains a slash. */
1583 execve (file, argv, envp);
1587 if (errno == ENOEXEC)
1588 script_execute (file, argv, envp, FALSE);
1592 gboolean got_eacces = 0;
1593 const gchar *path, *p;
1594 gchar *name, *freeme;
1598 path = g_getenv ("PATH");
1601 /* There is no `PATH' in the environment. The default
1602 * search path in libc is the current directory followed by
1603 * the path `confstr' returns for `_CS_PATH'.
1606 /* In GLib we put . last, for security, and don't use the
1607 * unportable confstr(); UNIX98 does not actually specify
1608 * what to search if PATH is unset. POSIX may, dunno.
1611 path = "/bin:/usr/bin:.";
1614 len = strlen (file) + 1;
1615 pathlen = strlen (path);
1616 freeme = name = g_malloc (pathlen + len + 1);
1618 /* Copy the file name at the top, including '\0' */
1619 memcpy (name + pathlen + 1, file, len);
1620 name = name + pathlen;
1621 /* And add the slash before the filename */
1630 p = my_strchrnul (path, ':');
1633 /* Two adjacent colons, or a colon at the beginning or the end
1634 * of `PATH' means to search the current directory.
1638 startp = memcpy (name - (p - path), path, p - path);
1640 /* Try to execute this name. If it works, execv will not return. */
1642 execve (startp, argv, envp);
1644 execv (startp, argv);
1646 if (errno == ENOEXEC)
1647 script_execute (startp, argv, envp, search_path);
1652 /* Record the we got a `Permission denied' error. If we end
1653 * up finding no executable we can use, we want to diagnose
1654 * that we did find one but were denied access.
1667 /* Those errors indicate the file is missing or not executable
1668 * by us, in which case we want to just try the next path
1674 /* Some other error means we found an executable file, but
1675 * something went wrong executing it; return the error to our
1682 while (*p++ != '\0');
1684 /* We tried every element and none of them worked. */
1686 /* At least one failure was due to permissions, so report that
1694 /* Return the error from the last attempt (probably ENOENT). */
1699 * g_spawn_close_pid:
1700 * @pid: The process reference to close
1702 * On some platforms, notably Windows, the #GPid type represents a resource
1703 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1704 * is provided for this purpose. It should be used on all platforms, even
1705 * though it doesn't do anything under UNIX.
1708 g_spawn_close_pid (GPid pid)