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,
68 gboolean search_path_from_envp);
70 static gboolean make_pipe (gint p[2],
72 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
73 const gchar *working_directory,
76 gboolean close_descriptors,
78 gboolean search_path_from_envp,
79 gboolean stdout_to_null,
80 gboolean stderr_to_null,
81 gboolean child_inherits_stdin,
82 gboolean file_and_argv_zero,
83 GSpawnChildSetupFunc child_setup,
87 gint *standard_output,
91 G_DEFINE_QUARK ("g-exec-error-quark", g_spawn_error)
92 G_DEFINE_QUARK ("g-spawn-exit-error-quark", g_spawn_exit_error)
96 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
97 * @argv: (array zero-terminated=1): child's argument vector
98 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
99 * @flags: flags from #GSpawnFlags
100 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
101 * @user_data: (closure): user data for @child_setup
102 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
103 * @error: return location for error
105 * See g_spawn_async_with_pipes() for a full description; this function
106 * simply calls the g_spawn_async_with_pipes() without any pipes.
108 * You should call g_spawn_close_pid() on the returned child process
109 * reference when you don't need it any more.
112 * If you are writing a GTK+ application, and the program you
113 * are spawning is a graphical application, too, then you may
114 * want to use gdk_spawn_on_screen() instead to ensure that
115 * the spawned program opens its windows on the right screen.
118 * <note><para> Note that the returned @child_pid on Windows is a
119 * handle to the child process and not its identifier. Process handles
120 * and process identifiers are different concepts on Windows.
123 * Return value: %TRUE on success, %FALSE if error is set
126 g_spawn_async (const gchar *working_directory,
130 GSpawnChildSetupFunc child_setup,
135 g_return_val_if_fail (argv != NULL, FALSE);
137 return g_spawn_async_with_pipes (working_directory,
147 /* Avoids a danger in threaded situations (calling close()
148 * on a file descriptor twice, and another thread has
149 * re-opened it since the first close)
152 close_and_invalidate (gint *fd)
162 if (ret == -1 && errno == EINTR)
170 /* Some versions of OS X define READ_OK in public headers */
175 READ_FAILED = 0, /* FALSE */
181 read_data (GString *str,
189 bytes = read (fd, buf, 4096);
195 g_string_append_len (str, buf, bytes);
198 else if (errno == EINTR)
207 _("Failed to read data from child process (%s)"),
216 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
217 * @argv: (array zero-terminated=1): child's argument vector
218 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
219 * @flags: flags from #GSpawnFlags
220 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
221 * @user_data: (closure): user data for @child_setup
222 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
223 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
224 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
225 * @error: return location for error, or %NULL
227 * Executes a child synchronously (waits for the child to exit before returning).
228 * All output from the child is stored in @standard_output and @standard_error,
229 * if those parameters are non-%NULL. Note that you must set the
230 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
231 * passing %NULL for @standard_output and @standard_error.
233 * If @exit_status is non-%NULL, the platform-specific exit status of
234 * the child is stored there; see the doucumentation of
235 * g_spawn_check_exit_status() for how to use and interpret this.
236 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
239 * If an error occurs, no data is returned in @standard_output,
240 * @standard_error, or @exit_status.
242 * This function calls g_spawn_async_with_pipes() internally; see that
243 * function for full details on the other parameters and details on
244 * how these functions work on Windows.
246 * Return value: %TRUE on success, %FALSE if an error was set.
249 g_spawn_sync (const gchar *working_directory,
253 GSpawnChildSetupFunc child_setup,
255 gchar **standard_output,
256 gchar **standard_error,
265 GString *outstr = NULL;
266 GString *errstr = NULL;
270 g_return_val_if_fail (argv != NULL, FALSE);
271 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
272 g_return_val_if_fail (standard_output == NULL ||
273 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
274 g_return_val_if_fail (standard_error == NULL ||
275 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
277 /* Just to ensure segfaults if callers try to use
278 * these when an error is reported.
281 *standard_output = NULL;
284 *standard_error = NULL;
286 if (!fork_exec_with_pipes (FALSE,
290 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
291 (flags & G_SPAWN_SEARCH_PATH) != 0,
292 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
293 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
294 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
295 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
296 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
301 standard_output ? &outpipe : NULL,
302 standard_error ? &errpipe : NULL,
306 /* Read data from child. */
312 outstr = g_string_new (NULL);
317 errstr = g_string_new (NULL);
320 /* Read data until we get EOF on both pipes. */
329 FD_SET (outpipe, &fds);
331 FD_SET (errpipe, &fds);
333 ret = select (MAX (outpipe, errpipe) + 1,
336 NULL /* no timeout */);
350 _("Unexpected error in select() reading data from a child process (%s)"),
356 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
358 switch (read_data (outstr, outpipe, error))
364 close_and_invalidate (&outpipe);
375 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
377 switch (read_data (errstr, errpipe, error))
383 close_and_invalidate (&errpipe);
395 /* These should only be open still if we had an error. */
398 close_and_invalidate (&outpipe);
400 close_and_invalidate (&errpipe);
402 /* Wait for child to exit, even if we have
407 ret = waitpid (pid, &status, 0);
413 else if (errno == ECHILD)
417 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.");
421 /* We don't need the exit status. */
426 if (!failed) /* avoid error pileups */
435 _("Unexpected error in waitpid() (%s)"),
444 g_string_free (outstr, TRUE);
446 g_string_free (errstr, TRUE);
453 *exit_status = status;
456 *standard_output = g_string_free (outstr, FALSE);
459 *standard_error = g_string_free (errstr, FALSE);
466 * g_spawn_async_with_pipes:
467 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
468 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
469 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
470 * @flags: flags from #GSpawnFlags
471 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
472 * @user_data: (closure): user data for @child_setup
473 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
474 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
475 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
476 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
477 * @error: return location for error
479 * Executes a child program asynchronously (your program will not
480 * block waiting for the child to exit). The child program is
481 * specified by the only argument that must be provided, @argv. @argv
482 * should be a %NULL-terminated array of strings, to be passed as the
483 * argument vector for the child. The first string in @argv is of
484 * course the name of the program to execute. By default, the name of
485 * the program must be a full path. If @flags contains the
486 * %G_SPAWN_SEARCH_PATH flag, the <envar>PATH</envar> environment variable
487 * is used to search for the executable. If @flags contains the
488 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the <envar>PATH</envar> variable from
489 * @envp is used to search for the executable.
490 * If both the %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
491 * flags are set, the <envar>PATH</envar> variable from @envp takes precedence
492 * over the environment variable.
494 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
495 * used, then the program will be run from the current directory (or
496 * @working_directory, if specified); this might be unexpected or even
497 * dangerous in some cases when the current directory is world-writable.
499 * On Windows, note that all the string or string vector arguments to
500 * this function and the other g_spawn*() functions are in UTF-8, the
501 * GLib file name encoding. Unicode characters that are not part of
502 * the system codepage passed in these arguments will be correctly
503 * available in the spawned program only if it uses wide character API
504 * to retrieve its command line. For C programs built with Microsoft's
505 * tools it is enough to make the program have a wmain() instead of
506 * main(). wmain() has a wide character argument vector as parameter.
508 * At least currently, mingw doesn't support wmain(), so if you use
509 * mingw to develop the spawned program, it will have to call the
510 * undocumented function __wgetmainargs() to get the wide character
511 * argument vector and environment. See gspawn-win32-helper.c in the
512 * GLib sources or init.c in the mingw runtime sources for a prototype
513 * for that function. Alternatively, you can retrieve the Win32 system
514 * level wide character command line passed to the spawned program
515 * using the GetCommandLineW() function.
517 * On Windows the low-level child process creation API
518 * <function>CreateProcess()</function> doesn't use argument vectors,
519 * but a command line. The C runtime library's
520 * <function>spawn*()</function> family of functions (which
521 * g_spawn_async_with_pipes() eventually calls) paste the argument
522 * vector elements together into a command line, and the C runtime startup code
523 * does a corresponding reconstruction of an argument vector from the
524 * command line, to be passed to main(). Complications arise when you have
525 * argument vector elements that contain spaces of double quotes. The
526 * <function>spawn*()</function> functions don't do any quoting or
527 * escaping, but on the other hand the startup code does do unquoting
528 * and unescaping in order to enable receiving arguments with embedded
529 * spaces or double quotes. To work around this asymmetry,
530 * g_spawn_async_with_pipes() will do quoting and escaping on argument
531 * vector elements that need it before calling the C runtime
534 * The returned @child_pid on Windows is a handle to the child
535 * process, not its identifier. Process handles and process
536 * identifiers are different concepts on Windows.
538 * @envp is a %NULL-terminated array of strings, where each string
539 * has the form <literal>KEY=VALUE</literal>. This will become
540 * the child's environment. If @envp is %NULL, the child inherits its
541 * parent's environment.
543 * @flags should be the bitwise OR of any flags you want to affect the
544 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
545 * child will not automatically be reaped; you must use a child watch to
546 * be notified about the death of the child process. Eventually you must
547 * call g_spawn_close_pid() on the @child_pid, in order to free
548 * resources which may be associated with the child process. (On Unix,
549 * using a child watch is equivalent to calling waitpid() or handling
550 * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
551 * is equivalent to calling CloseHandle() on the process handle returned
552 * in @child_pid). See g_child_watch_add().
554 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
555 * descriptors will be inherited by the child; otherwise all
556 * descriptors except stdin/stdout/stderr will be closed before
557 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
558 * means that <literal>argv[0]</literal> need not be an absolute path, it
559 * will be looked for in the <envar>PATH</envar> environment variable.
560 * %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an absolute path, it
561 * will be looked for in the <envar>PATH</envar> variable from @envp. If
562 * both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP are used,
563 * the value from @envp takes precedence over the environment.
564 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
565 * be discarded, instead of going to the same location as the parent's
566 * standard output. If you use this flag, @standard_output must be %NULL.
567 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
568 * will be discarded, instead of going to the same location as the parent's
569 * standard error. If you use this flag, @standard_error must be %NULL.
570 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
571 * standard input (by default, the child's standard input is attached to
572 * /dev/null). If you use this flag, @standard_input must be %NULL.
573 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
574 * the file to execute, while the remaining elements are the
575 * actual argument vector to pass to the file. Normally
576 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
577 * passes all of @argv to the child.
579 * @child_setup and @user_data are a function and user data. On POSIX
580 * platforms, the function is called in the child after GLib has
581 * performed all the setup it plans to perform (including creating
582 * pipes, closing file descriptors, etc.) but before calling
583 * exec(). That is, @child_setup is called just
584 * before calling exec() in the child. Obviously
585 * actions taken in this function will only affect the child, not the
588 * On Windows, there is no separate fork() and exec()
589 * functionality. Child processes are created and run with a single
590 * API call, CreateProcess(). There is no sensible thing @child_setup
591 * could be used for on Windows so it is ignored and not called.
593 * If non-%NULL, @child_pid will on Unix be filled with the child's
594 * process ID. You can use the process ID to send signals to the
595 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
596 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
597 * filled with a handle to the child process only if you specified the
598 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
599 * process using the Win32 API, for example wait for its termination
600 * with the <function>WaitFor*()</function> functions, or examine its
601 * exit code with GetExitCodeProcess(). You should close the handle
602 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
604 * If non-%NULL, the @standard_input, @standard_output, @standard_error
605 * locations will be filled with file descriptors for writing to the child's
606 * standard input or reading from its standard output or standard error.
607 * The caller of g_spawn_async_with_pipes() must close these file descriptors
608 * when they are no longer in use. If these parameters are %NULL, the corresponding
609 * pipe won't be created.
611 * If @standard_input is NULL, the child's standard input is attached to
612 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
614 * If @standard_error is NULL, the child's standard error goes to the same
615 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
618 * If @standard_output is NULL, the child's standard output goes to the same
619 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
622 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
623 * If an error is set, the function returns %FALSE. Errors
624 * are reported even if they occur in the child (for example if the
625 * executable in <literal>argv[0]</literal> is not found). Typically
626 * the <literal>message</literal> field of returned errors should be displayed
627 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
629 * If an error occurs, @child_pid, @standard_input, @standard_output,
630 * and @standard_error will not be filled with valid values.
632 * If @child_pid is not %NULL and an error does not occur then the returned
633 * process reference must be closed using g_spawn_close_pid().
636 * If you are writing a GTK+ application, and the program you
637 * are spawning is a graphical application, too, then you may
638 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
639 * the spawned program opens its windows on the right screen.
642 * Return value: %TRUE on success, %FALSE if an error was set
645 g_spawn_async_with_pipes (const gchar *working_directory,
649 GSpawnChildSetupFunc child_setup,
652 gint *standard_input,
653 gint *standard_output,
654 gint *standard_error,
657 g_return_val_if_fail (argv != NULL, FALSE);
658 g_return_val_if_fail (standard_output == NULL ||
659 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
660 g_return_val_if_fail (standard_error == NULL ||
661 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
662 /* can't inherit stdin if we have an input pipe. */
663 g_return_val_if_fail (standard_input == NULL ||
664 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
666 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
670 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
671 (flags & G_SPAWN_SEARCH_PATH) != 0,
672 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
673 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
674 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
675 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
676 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
687 * g_spawn_command_line_sync:
688 * @command_line: a command line
689 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
690 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
691 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
692 * @error: return location for errors
694 * A simple version of g_spawn_sync() with little-used parameters
695 * removed, taking a command line instead of an argument vector. See
696 * g_spawn_sync() for full details. @command_line will be parsed by
697 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
698 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
699 * implications, so consider using g_spawn_sync() directly if
700 * appropriate. Possible errors are those from g_spawn_sync() and those
701 * from g_shell_parse_argv().
703 * If @exit_status is non-%NULL, the platform-specific exit status of
704 * the child is stored there; see the documentation of
705 * g_spawn_check_exit_status() for how to use and interpret this.
707 * On Windows, please note the implications of g_shell_parse_argv()
708 * parsing @command_line. Parsing is done according to Unix shell rules, not
709 * Windows command interpreter rules.
710 * Space is a separator, and backslashes are
711 * special. Thus you cannot simply pass a @command_line containing
712 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
713 * the backslashes will be eaten, and the space will act as a
714 * separator. You need to enclose such paths with single quotes, like
715 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
717 * Return value: %TRUE on success, %FALSE if an error was set
720 g_spawn_command_line_sync (const gchar *command_line,
721 gchar **standard_output,
722 gchar **standard_error,
729 g_return_val_if_fail (command_line != NULL, FALSE);
731 if (!g_shell_parse_argv (command_line,
736 retval = g_spawn_sync (NULL,
752 * g_spawn_command_line_async:
753 * @command_line: a command line
754 * @error: return location for errors
756 * A simple version of g_spawn_async() that parses a command line with
757 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
758 * command line in the background. Unlike g_spawn_async(), the
759 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
760 * that %G_SPAWN_SEARCH_PATH can have security implications, so
761 * consider using g_spawn_async() directly if appropriate. Possible
762 * errors are those from g_shell_parse_argv() and g_spawn_async().
764 * The same concerns on Windows apply as for g_spawn_command_line_sync().
766 * Return value: %TRUE on success, %FALSE if error is set.
769 g_spawn_command_line_async (const gchar *command_line,
775 g_return_val_if_fail (command_line != NULL, FALSE);
777 if (!g_shell_parse_argv (command_line,
782 retval = g_spawn_async (NULL,
796 * g_spawn_check_exit_status:
797 * @exit_status: An exit code as returned from g_spawn_sync()
800 * Set @error if @exit_status indicates the child exited abnormally
801 * (e.g. with a nonzero exit code, or via a fatal signal).
803 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
804 * exit status for subprocesses encoded in a platform-specific way.
805 * On Unix, this is guaranteed to be in the same format
806 * <literal>waitpid(2)</literal> returns, and on Windows it is
807 * guaranteed to be the result of
808 * <literal>GetExitCodeProcess()</literal>. Prior to the introduction
809 * of this function in GLib 2.34, interpreting @exit_status required
810 * use of platform-specific APIs, which is problematic for software
811 * using GLib as a cross-platform layer.
813 * Additionally, many programs simply want to determine whether or not
814 * the child exited successfully, and either propagate a #GError or
815 * print a message to standard error. In that common case, this
816 * function can be used. Note that the error message in @error will
817 * contain human-readable information about the exit status.
819 * The <literal>domain</literal> and <literal>code</literal> of @error
820 * have special semantics in the case where the process has an "exit
821 * code", as opposed to being killed by a signal. On Unix, this
822 * happens if <literal>WIFEXITED</literal> would be true of
823 * @exit_status. On Windows, it is always the case.
825 * The special semantics are that the actual exit code will be the
826 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
827 * This allows you to differentiate between different exit codes.
829 * If the process was terminated by some means other than an exit
830 * status, the domain will be %G_SPAWN_ERROR, and the code will be
831 * %G_SPAWN_ERROR_FAILED.
833 * This function just offers convenience; you can of course also check
834 * the available platform via a macro such as %G_OS_UNIX, and use
835 * <literal>WIFEXITED()</literal> and <literal>WEXITSTATUS()</literal>
836 * on @exit_status directly. Do not attempt to scan or parse the
837 * error message string; it may be translated and/or change in future
840 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and @error will be set)
844 g_spawn_check_exit_status (gint exit_status,
847 gboolean ret = FALSE;
849 if (WIFEXITED (exit_status))
851 if (WEXITSTATUS (exit_status) != 0)
853 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
854 _("Child process exited with code %ld"),
855 (long) WEXITSTATUS (exit_status));
859 else if (WIFSIGNALED (exit_status))
861 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
862 _("Child process killed by signal %ld"),
863 (long) WTERMSIG (exit_status));
866 else if (WIFSTOPPED (exit_status))
868 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
869 _("Child process stopped by signal %ld"),
870 (long) WSTOPSIG (exit_status));
875 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
876 _("Child process exited abnormally"));
886 exec_err_to_g_error (gint en)
892 return G_SPAWN_ERROR_ACCES;
898 return G_SPAWN_ERROR_PERM;
904 return G_SPAWN_ERROR_TOO_BIG;
910 return G_SPAWN_ERROR_NOEXEC;
916 return G_SPAWN_ERROR_NAMETOOLONG;
922 return G_SPAWN_ERROR_NOENT;
928 return G_SPAWN_ERROR_NOMEM;
934 return G_SPAWN_ERROR_NOTDIR;
940 return G_SPAWN_ERROR_LOOP;
946 return G_SPAWN_ERROR_TXTBUSY;
952 return G_SPAWN_ERROR_IO;
958 return G_SPAWN_ERROR_NFILE;
964 return G_SPAWN_ERROR_MFILE;
970 return G_SPAWN_ERROR_INVAL;
976 return G_SPAWN_ERROR_ISDIR;
982 return G_SPAWN_ERROR_LIBBAD;
987 return G_SPAWN_ERROR_FAILED;
993 write_all (gint fd, gconstpointer vbuf, gsize to_write)
995 gchar *buf = (gchar *) vbuf;
999 gssize count = write (fd, buf, to_write);
1017 write_err_and_exit (gint fd, gint msg)
1021 write_all (fd, &msg, sizeof(msg));
1022 write_all (fd, &en, sizeof(en));
1028 set_cloexec (void *data, gint fd)
1030 if (fd >= GPOINTER_TO_INT (data))
1031 fcntl (fd, F_SETFD, FD_CLOEXEC);
1038 fdwalk (int (*cb)(void *data, int fd), void *data)
1044 #ifdef HAVE_SYS_RESOURCE_H
1051 if ((d = opendir("/proc/self/fd"))) {
1054 while ((de = readdir(d))) {
1058 if (de->d_name[0] == '.')
1062 l = strtol(de->d_name, &e, 10);
1063 if (errno != 0 || !e || *e)
1068 if ((glong) fd != l)
1074 if ((res = cb (data, fd)) != 0)
1082 /* If /proc is not mounted or not accessible we fall back to the old
1087 #ifdef HAVE_SYS_RESOURCE_H
1089 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1090 open_max = rl.rlim_max;
1093 open_max = sysconf (_SC_OPEN_MAX);
1095 for (fd = 0; fd < open_max; fd++)
1096 if ((res = cb (data, fd)) != 0)
1104 sane_dup2 (gint fd1, gint fd2)
1109 ret = dup2 (fd1, fd2);
1110 if (ret < 0 && errno == EINTR)
1117 sane_open (const char *path, gint mode)
1122 ret = open (path, mode);
1123 if (ret < 0 && errno == EINTR)
1138 do_exec (gint child_err_report_fd,
1142 const gchar *working_directory,
1145 gboolean close_descriptors,
1146 gboolean search_path,
1147 gboolean search_path_from_envp,
1148 gboolean stdout_to_null,
1149 gboolean stderr_to_null,
1150 gboolean child_inherits_stdin,
1151 gboolean file_and_argv_zero,
1152 GSpawnChildSetupFunc child_setup,
1155 if (working_directory && chdir (working_directory) < 0)
1156 write_err_and_exit (child_err_report_fd,
1157 CHILD_CHDIR_FAILED);
1159 /* Close all file descriptors but stdin stdout and stderr as
1160 * soon as we exec. Note that this includes
1161 * child_err_report_fd, which keeps the parent from blocking
1162 * forever on the other end of that pipe.
1164 if (close_descriptors)
1166 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1170 /* We need to do child_err_report_fd anyway */
1171 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1174 /* Redirect pipes as required */
1178 /* dup2 can't actually fail here I don't think */
1180 if (sane_dup2 (stdin_fd, 0) < 0)
1181 write_err_and_exit (child_err_report_fd,
1184 /* ignore this if it doesn't work */
1185 close_and_invalidate (&stdin_fd);
1187 else if (!child_inherits_stdin)
1189 /* Keep process from blocking on a read of stdin */
1190 gint read_null = open ("/dev/null", O_RDONLY);
1191 g_assert (read_null != -1);
1192 sane_dup2 (read_null, 0);
1193 close_and_invalidate (&read_null);
1198 /* dup2 can't actually fail here I don't think */
1200 if (sane_dup2 (stdout_fd, 1) < 0)
1201 write_err_and_exit (child_err_report_fd,
1204 /* ignore this if it doesn't work */
1205 close_and_invalidate (&stdout_fd);
1207 else if (stdout_to_null)
1209 gint write_null = sane_open ("/dev/null", O_WRONLY);
1210 g_assert (write_null != -1);
1211 sane_dup2 (write_null, 1);
1212 close_and_invalidate (&write_null);
1217 /* dup2 can't actually fail here I don't think */
1219 if (sane_dup2 (stderr_fd, 2) < 0)
1220 write_err_and_exit (child_err_report_fd,
1223 /* ignore this if it doesn't work */
1224 close_and_invalidate (&stderr_fd);
1226 else if (stderr_to_null)
1228 gint write_null = sane_open ("/dev/null", O_WRONLY);
1229 sane_dup2 (write_null, 2);
1230 close_and_invalidate (&write_null);
1233 /* Call user function just before we exec */
1236 (* child_setup) (user_data);
1240 file_and_argv_zero ? argv + 1 : argv,
1241 envp, search_path, search_path_from_envp);
1244 write_err_and_exit (child_err_report_fd,
1261 if (bytes >= sizeof(gint)*2)
1262 break; /* give up, who knows what happened, should not be
1268 ((gchar*)buf) + bytes,
1269 sizeof(gint) * n_ints_in_buf - bytes);
1270 if (chunk < 0 && errno == EINTR)
1277 /* Some weird shit happened, bail out */
1280 G_SPAWN_ERROR_FAILED,
1281 _("Failed to read from child pipe (%s)"),
1282 g_strerror (errsv));
1286 else if (chunk == 0)
1288 else /* chunk > 0 */
1292 *n_ints_read = (gint)(bytes / sizeof(gint));
1298 fork_exec_with_pipes (gboolean intermediate_child,
1299 const gchar *working_directory,
1302 gboolean close_descriptors,
1303 gboolean search_path,
1304 gboolean search_path_from_envp,
1305 gboolean stdout_to_null,
1306 gboolean stderr_to_null,
1307 gboolean child_inherits_stdin,
1308 gboolean file_and_argv_zero,
1309 GSpawnChildSetupFunc child_setup,
1312 gint *standard_input,
1313 gint *standard_output,
1314 gint *standard_error,
1318 gint stdin_pipe[2] = { -1, -1 };
1319 gint stdout_pipe[2] = { -1, -1 };
1320 gint stderr_pipe[2] = { -1, -1 };
1321 gint child_err_report_pipe[2] = { -1, -1 };
1322 gint child_pid_report_pipe[2] = { -1, -1 };
1325 if (!make_pipe (child_err_report_pipe, error))
1328 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1329 goto cleanup_and_fail;
1331 if (standard_input && !make_pipe (stdin_pipe, error))
1332 goto cleanup_and_fail;
1334 if (standard_output && !make_pipe (stdout_pipe, error))
1335 goto cleanup_and_fail;
1337 if (standard_error && !make_pipe (stderr_pipe, error))
1338 goto cleanup_and_fail;
1349 _("Failed to fork (%s)"),
1350 g_strerror (errsv));
1352 goto cleanup_and_fail;
1356 /* Immediate child. This may or may not be the child that
1357 * actually execs the new process.
1360 /* Reset some signal handlers that we may use */
1361 signal (SIGCHLD, SIG_DFL);
1362 signal (SIGINT, SIG_DFL);
1363 signal (SIGTERM, SIG_DFL);
1364 signal (SIGHUP, SIG_DFL);
1366 /* Be sure we crash if the parent exits
1367 * and we write to the err_report_pipe
1369 signal (SIGPIPE, SIG_DFL);
1371 /* Close the parent's end of the pipes;
1372 * not needed in the close_descriptors case,
1375 close_and_invalidate (&child_err_report_pipe[0]);
1376 close_and_invalidate (&child_pid_report_pipe[0]);
1377 close_and_invalidate (&stdin_pipe[1]);
1378 close_and_invalidate (&stdout_pipe[0]);
1379 close_and_invalidate (&stderr_pipe[0]);
1381 if (intermediate_child)
1383 /* We need to fork an intermediate child that launches the
1384 * final child. The purpose of the intermediate child
1385 * is to exit, so we can waitpid() it immediately.
1386 * Then the grandchild will not become a zombie.
1388 GPid grandchild_pid;
1390 grandchild_pid = fork ();
1392 if (grandchild_pid < 0)
1394 /* report -1 as child PID */
1395 write_all (child_pid_report_pipe[1], &grandchild_pid,
1396 sizeof(grandchild_pid));
1398 write_err_and_exit (child_err_report_pipe[1],
1401 else if (grandchild_pid == 0)
1403 do_exec (child_err_report_pipe[1],
1412 search_path_from_envp,
1415 child_inherits_stdin,
1422 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1423 close_and_invalidate (&child_pid_report_pipe[1]);
1430 /* Just run the child.
1433 do_exec (child_err_report_pipe[1],
1442 search_path_from_envp,
1445 child_inherits_stdin,
1458 /* Close the uncared-about ends of the pipes */
1459 close_and_invalidate (&child_err_report_pipe[1]);
1460 close_and_invalidate (&child_pid_report_pipe[1]);
1461 close_and_invalidate (&stdin_pipe[0]);
1462 close_and_invalidate (&stdout_pipe[1]);
1463 close_and_invalidate (&stderr_pipe[1]);
1465 /* If we had an intermediate child, reap it */
1466 if (intermediate_child)
1469 if (waitpid (pid, &status, 0) < 0)
1473 else if (errno == ECHILD)
1474 ; /* do nothing, child already reaped */
1476 g_warning ("waitpid() should not fail in "
1477 "'fork_exec_with_pipes'");
1482 if (!read_ints (child_err_report_pipe[0],
1485 goto cleanup_and_fail;
1489 /* Error from the child. */
1493 case CHILD_CHDIR_FAILED:
1496 G_SPAWN_ERROR_CHDIR,
1497 _("Failed to change to directory '%s' (%s)"),
1499 g_strerror (buf[1]));
1503 case CHILD_EXEC_FAILED:
1506 exec_err_to_g_error (buf[1]),
1507 _("Failed to execute child process \"%s\" (%s)"),
1509 g_strerror (buf[1]));
1513 case CHILD_DUP2_FAILED:
1516 G_SPAWN_ERROR_FAILED,
1517 _("Failed to redirect output or input of child process (%s)"),
1518 g_strerror (buf[1]));
1522 case CHILD_FORK_FAILED:
1526 _("Failed to fork child process (%s)"),
1527 g_strerror (buf[1]));
1533 G_SPAWN_ERROR_FAILED,
1534 _("Unknown error executing child process \"%s\""),
1539 goto cleanup_and_fail;
1542 /* Get child pid from intermediate child pipe. */
1543 if (intermediate_child)
1547 if (!read_ints (child_pid_report_pipe[0],
1548 buf, 1, &n_ints, error))
1549 goto cleanup_and_fail;
1557 G_SPAWN_ERROR_FAILED,
1558 _("Failed to read enough data from child pid pipe (%s)"),
1559 g_strerror (errsv));
1560 goto cleanup_and_fail;
1564 /* we have the child pid */
1569 /* Success against all odds! return the information */
1570 close_and_invalidate (&child_err_report_pipe[0]);
1571 close_and_invalidate (&child_pid_report_pipe[0]);
1577 *standard_input = stdin_pipe[1];
1578 if (standard_output)
1579 *standard_output = stdout_pipe[0];
1581 *standard_error = stderr_pipe[0];
1588 /* There was an error from the Child, reap the child to avoid it being
1595 if (waitpid (pid, NULL, 0) < 0)
1599 else if (errno == ECHILD)
1600 ; /* do nothing, child already reaped */
1602 g_warning ("waitpid() should not fail in "
1603 "'fork_exec_with_pipes'");
1607 close_and_invalidate (&child_err_report_pipe[0]);
1608 close_and_invalidate (&child_err_report_pipe[1]);
1609 close_and_invalidate (&child_pid_report_pipe[0]);
1610 close_and_invalidate (&child_pid_report_pipe[1]);
1611 close_and_invalidate (&stdin_pipe[0]);
1612 close_and_invalidate (&stdin_pipe[1]);
1613 close_and_invalidate (&stdout_pipe[0]);
1614 close_and_invalidate (&stdout_pipe[1]);
1615 close_and_invalidate (&stderr_pipe[0]);
1616 close_and_invalidate (&stderr_pipe[1]);
1622 make_pipe (gint p[2],
1630 G_SPAWN_ERROR_FAILED,
1631 _("Failed to create pipe for communicating with child process (%s)"),
1632 g_strerror (errsv));
1639 /* Based on execvp from GNU C Library */
1642 script_execute (const gchar *file,
1646 /* Count the arguments. */
1651 /* Construct an argument list for the shell. */
1655 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1657 new_argv[0] = (char *) "/bin/sh";
1658 new_argv[1] = (char *) file;
1661 new_argv[argc + 1] = argv[argc];
1665 /* Execute the shell. */
1667 execve (new_argv[0], new_argv, envp);
1669 execv (new_argv[0], new_argv);
1676 my_strchrnul (const gchar *str, gchar c)
1678 gchar *p = (gchar*) str;
1679 while (*p && (*p != c))
1686 g_execute (const gchar *file,
1689 gboolean search_path,
1690 gboolean search_path_from_envp)
1694 /* We check the simple case first. */
1699 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1701 /* Don't search when it contains a slash. */
1703 execve (file, argv, envp);
1707 if (errno == ENOEXEC)
1708 script_execute (file, argv, envp);
1712 gboolean got_eacces = 0;
1713 const gchar *path, *p;
1714 gchar *name, *freeme;
1719 if (search_path_from_envp)
1720 path = g_environ_getenv (envp, "PATH");
1721 if (search_path && path == NULL)
1722 path = g_getenv ("PATH");
1726 /* There is no `PATH' in the environment. The default
1727 * search path in libc is the current directory followed by
1728 * the path `confstr' returns for `_CS_PATH'.
1731 /* In GLib we put . last, for security, and don't use the
1732 * unportable confstr(); UNIX98 does not actually specify
1733 * what to search if PATH is unset. POSIX may, dunno.
1736 path = "/bin:/usr/bin:.";
1739 len = strlen (file) + 1;
1740 pathlen = strlen (path);
1741 freeme = name = g_malloc (pathlen + len + 1);
1743 /* Copy the file name at the top, including '\0' */
1744 memcpy (name + pathlen + 1, file, len);
1745 name = name + pathlen;
1746 /* And add the slash before the filename */
1755 p = my_strchrnul (path, ':');
1758 /* Two adjacent colons, or a colon at the beginning or the end
1759 * of `PATH' means to search the current directory.
1763 startp = memcpy (name - (p - path), path, p - path);
1765 /* Try to execute this name. If it works, execv will not return. */
1767 execve (startp, argv, envp);
1769 execv (startp, argv);
1771 if (errno == ENOEXEC)
1772 script_execute (startp, argv, envp);
1777 /* Record the we got a `Permission denied' error. If we end
1778 * up finding no executable we can use, we want to diagnose
1779 * that we did find one but were denied access.
1792 /* Those errors indicate the file is missing or not executable
1793 * by us, in which case we want to just try the next path
1800 /* Some strange filesystems like AFS return even
1801 * stranger error numbers. They cannot reasonably mean anything
1802 * else so ignore those, too.
1807 /* Some other error means we found an executable file, but
1808 * something went wrong executing it; return the error to our
1815 while (*p++ != '\0');
1817 /* We tried every element and none of them worked. */
1819 /* At least one failure was due to permissions, so report that
1827 /* Return the error from the last attempt (probably ENOENT). */
1832 * g_spawn_close_pid:
1833 * @pid: The process reference to close
1835 * On some platforms, notably Windows, the #GPid type represents a resource
1836 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1837 * is provided for this purpose. It should be used on all platforms, even
1838 * though it doesn't do anything under UNIX.
1841 g_spawn_close_pid (GPid pid)