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 */
46 #include "glib/gstdio.h"
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
56 #include "glib-unix.h"
60 * @Short_description: process launching
61 * @Title: Spawning Processes
66 static gint g_execute (const gchar *file,
70 gboolean search_path_from_envp);
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 gboolean cloexec_pipes,
84 GSpawnChildSetupFunc child_setup,
88 gint *standard_output,
92 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
93 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
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)
159 (void) g_close (*fd, NULL);
164 /* Some versions of OS X define READ_OK in public headers */
169 READ_FAILED = 0, /* FALSE */
175 read_data (GString *str,
183 bytes = read (fd, buf, 4096);
189 g_string_append_len (str, buf, bytes);
192 else if (errno == EINTR)
201 _("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.
227 * If @exit_status is non-%NULL, the platform-specific exit status of
228 * the child is stored there; see the documentation of
229 * g_spawn_check_exit_status() for how to use and interpret this.
230 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
233 * If an error occurs, no data is returned in @standard_output,
234 * @standard_error, or @exit_status.
236 * This function calls g_spawn_async_with_pipes() internally; see that
237 * function for full details on the other parameters and details on
238 * how these functions work on Windows.
240 * Return value: %TRUE on success, %FALSE if an error was set.
243 g_spawn_sync (const gchar *working_directory,
247 GSpawnChildSetupFunc child_setup,
249 gchar **standard_output,
250 gchar **standard_error,
259 GString *outstr = NULL;
260 GString *errstr = NULL;
264 g_return_val_if_fail (argv != NULL, FALSE);
265 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
266 g_return_val_if_fail (standard_output == NULL ||
267 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
268 g_return_val_if_fail (standard_error == NULL ||
269 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
271 /* Just to ensure segfaults if callers try to use
272 * these when an error is reported.
275 *standard_output = NULL;
278 *standard_error = NULL;
280 if (!fork_exec_with_pipes (FALSE,
284 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
285 (flags & G_SPAWN_SEARCH_PATH) != 0,
286 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
287 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
288 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
289 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
290 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
291 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
296 standard_output ? &outpipe : NULL,
297 standard_error ? &errpipe : NULL,
301 /* Read data from child. */
307 outstr = g_string_new (NULL);
312 errstr = g_string_new (NULL);
315 /* Read data until we get EOF on both pipes. */
324 FD_SET (outpipe, &fds);
326 FD_SET (errpipe, &fds);
328 ret = select (MAX (outpipe, errpipe) + 1,
331 NULL /* no timeout */);
345 _("Unexpected error in select() reading data from a child process (%s)"),
351 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
353 switch (read_data (outstr, outpipe, error))
359 close_and_invalidate (&outpipe);
370 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
372 switch (read_data (errstr, errpipe, error))
378 close_and_invalidate (&errpipe);
390 /* These should only be open still if we had an error. */
393 close_and_invalidate (&outpipe);
395 close_and_invalidate (&errpipe);
397 /* Wait for child to exit, even if we have
402 ret = waitpid (pid, &status, 0);
408 else if (errno == ECHILD)
412 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_spawn_sync either directly or indirectly.");
416 /* We don't need the exit status. */
421 if (!failed) /* avoid error pileups */
430 _("Unexpected error in waitpid() (%s)"),
439 g_string_free (outstr, TRUE);
441 g_string_free (errstr, TRUE);
448 *exit_status = status;
451 *standard_output = g_string_free (outstr, FALSE);
454 *standard_error = g_string_free (errstr, FALSE);
461 * g_spawn_async_with_pipes:
462 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
463 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
464 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
465 * @flags: flags from #GSpawnFlags
466 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
467 * @user_data: (closure): user data for @child_setup
468 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
469 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
470 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
471 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
472 * @error: return location for error
474 * Executes a child program asynchronously (your program will not
475 * block waiting for the child to exit). The child program is
476 * specified by the only argument that must be provided, @argv. @argv
477 * should be a %NULL-terminated array of strings, to be passed as the
478 * argument vector for the child. The first string in @argv is of
479 * course the name of the program to execute. By default, the name of
480 * the program must be a full path. If @flags contains the
481 * %G_SPAWN_SEARCH_PATH flag, the <envar>PATH</envar> environment variable
482 * is used to search for the executable. If @flags contains the
483 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the <envar>PATH</envar> variable from
484 * @envp is used to search for the executable.
485 * If both the %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
486 * flags are set, the <envar>PATH</envar> variable from @envp takes precedence
487 * over the environment variable.
489 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
490 * used, then the program will be run from the current directory (or
491 * @working_directory, if specified); this might be unexpected or even
492 * dangerous in some cases when the current directory is world-writable.
494 * On Windows, note that all the string or string vector arguments to
495 * this function and the other g_spawn*() functions are in UTF-8, the
496 * GLib file name encoding. Unicode characters that are not part of
497 * the system codepage passed in these arguments will be correctly
498 * available in the spawned program only if it uses wide character API
499 * to retrieve its command line. For C programs built with Microsoft's
500 * tools it is enough to make the program have a wmain() instead of
501 * main(). wmain() has a wide character argument vector as parameter.
503 * At least currently, mingw doesn't support wmain(), so if you use
504 * mingw to develop the spawned program, it will have to call the
505 * undocumented function __wgetmainargs() to get the wide character
506 * argument vector and environment. See gspawn-win32-helper.c in the
507 * GLib sources or init.c in the mingw runtime sources for a prototype
508 * for that function. Alternatively, you can retrieve the Win32 system
509 * level wide character command line passed to the spawned program
510 * using the GetCommandLineW() function.
512 * On Windows the low-level child process creation API
513 * <function>CreateProcess()</function> doesn't use argument vectors,
514 * but a command line. The C runtime library's
515 * <function>spawn*()</function> family of functions (which
516 * g_spawn_async_with_pipes() eventually calls) paste the argument
517 * vector elements together into a command line, and the C runtime startup code
518 * does a corresponding reconstruction of an argument vector from the
519 * command line, to be passed to main(). Complications arise when you have
520 * argument vector elements that contain spaces of double quotes. The
521 * <function>spawn*()</function> functions don't do any quoting or
522 * escaping, but on the other hand the startup code does do unquoting
523 * and unescaping in order to enable receiving arguments with embedded
524 * spaces or double quotes. To work around this asymmetry,
525 * g_spawn_async_with_pipes() will do quoting and escaping on argument
526 * vector elements that need it before calling the C runtime
529 * The returned @child_pid on Windows is a handle to the child
530 * process, not its identifier. Process handles and process
531 * identifiers are different concepts on Windows.
533 * @envp is a %NULL-terminated array of strings, where each string
534 * has the form <literal>KEY=VALUE</literal>. This will become
535 * the child's environment. If @envp is %NULL, the child inherits its
536 * parent's environment.
538 * @flags should be the bitwise OR of any flags you want to affect the
539 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
540 * child will not automatically be reaped; you must use a child watch to
541 * be notified about the death of the child process. Eventually you must
542 * call g_spawn_close_pid() on the @child_pid, in order to free
543 * resources which may be associated with the child process. (On Unix,
544 * using a child watch is equivalent to calling waitpid() or handling
545 * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
546 * is equivalent to calling CloseHandle() on the process handle returned
547 * in @child_pid). See g_child_watch_add().
549 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
550 * descriptors will be inherited by the child; otherwise all
551 * descriptors except stdin/stdout/stderr will be closed before
552 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
553 * means that <literal>argv[0]</literal> need not be an absolute path, it
554 * will be looked for in the <envar>PATH</envar> environment variable.
555 * %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an absolute path, it
556 * will be looked for in the <envar>PATH</envar> variable from @envp. If
557 * both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP are used,
558 * the value from @envp takes precedence over the environment.
559 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
560 * be discarded, instead of going to the same location as the parent's
561 * standard output. If you use this flag, @standard_output must be %NULL.
562 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
563 * will be discarded, instead of going to the same location as the parent's
564 * standard error. If you use this flag, @standard_error must be %NULL.
565 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
566 * standard input (by default, the child's standard input is attached to
567 * /dev/null). If you use this flag, @standard_input must be %NULL.
568 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
569 * the file to execute, while the remaining elements are the
570 * actual argument vector to pass to the file. Normally
571 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
572 * passes all of @argv to the child.
574 * @child_setup and @user_data are a function and user data. On POSIX
575 * platforms, the function is called in the child after GLib has
576 * performed all the setup it plans to perform (including creating
577 * pipes, closing file descriptors, etc.) but before calling
578 * exec(). That is, @child_setup is called just
579 * before calling exec() in the child. Obviously
580 * actions taken in this function will only affect the child, not the
583 * On Windows, there is no separate fork() and exec()
584 * functionality. Child processes are created and run with a single
585 * API call, CreateProcess(). There is no sensible thing @child_setup
586 * could be used for on Windows so it is ignored and not called.
588 * If non-%NULL, @child_pid will on Unix be filled with the child's
589 * process ID. You can use the process ID to send signals to the
590 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
591 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
592 * filled with a handle to the child process only if you specified the
593 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
594 * process using the Win32 API, for example wait for its termination
595 * with the <function>WaitFor*()</function> functions, or examine its
596 * exit code with GetExitCodeProcess(). You should close the handle
597 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
599 * If non-%NULL, the @standard_input, @standard_output, @standard_error
600 * locations will be filled with file descriptors for writing to the child's
601 * standard input or reading from its standard output or standard error.
602 * The caller of g_spawn_async_with_pipes() must close these file descriptors
603 * when they are no longer in use. If these parameters are %NULL, the corresponding
604 * pipe won't be created.
606 * If @standard_input is NULL, the child's standard input is attached to
607 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
609 * If @standard_error is NULL, the child's standard error goes to the same
610 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
613 * If @standard_output is NULL, the child's standard output goes to the same
614 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
617 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
618 * If an error is set, the function returns %FALSE. Errors
619 * are reported even if they occur in the child (for example if the
620 * executable in <literal>argv[0]</literal> is not found). Typically
621 * the <literal>message</literal> field of returned errors should be displayed
622 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
624 * If an error occurs, @child_pid, @standard_input, @standard_output,
625 * and @standard_error will not be filled with valid values.
627 * If @child_pid is not %NULL and an error does not occur then the returned
628 * process reference must be closed using g_spawn_close_pid().
631 * If you are writing a GTK+ application, and the program you
632 * are spawning is a graphical application, too, then you may
633 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
634 * the spawned program opens its windows on the right screen.
637 * Return value: %TRUE on success, %FALSE if an error was set
640 g_spawn_async_with_pipes (const gchar *working_directory,
644 GSpawnChildSetupFunc child_setup,
647 gint *standard_input,
648 gint *standard_output,
649 gint *standard_error,
652 g_return_val_if_fail (argv != NULL, FALSE);
653 g_return_val_if_fail (standard_output == NULL ||
654 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
655 g_return_val_if_fail (standard_error == NULL ||
656 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
657 /* can't inherit stdin if we have an input pipe. */
658 g_return_val_if_fail (standard_input == NULL ||
659 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
661 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
665 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
666 (flags & G_SPAWN_SEARCH_PATH) != 0,
667 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
668 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
669 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
670 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
671 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
672 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
683 * g_spawn_command_line_sync:
684 * @command_line: a command line
685 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
686 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
687 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
688 * @error: return location for errors
690 * A simple version of g_spawn_sync() with little-used parameters
691 * removed, taking a command line instead of an argument vector. See
692 * g_spawn_sync() for full details. @command_line will be parsed by
693 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
694 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
695 * implications, so consider using g_spawn_sync() directly if
696 * appropriate. Possible errors are those from g_spawn_sync() and those
697 * from g_shell_parse_argv().
699 * If @exit_status is non-%NULL, the platform-specific exit status of
700 * the child is stored there; see the documentation of
701 * g_spawn_check_exit_status() for how to use and interpret this.
703 * On Windows, please note the implications of g_shell_parse_argv()
704 * parsing @command_line. Parsing is done according to Unix shell rules, not
705 * Windows command interpreter rules.
706 * Space is a separator, and backslashes are
707 * special. Thus you cannot simply pass a @command_line containing
708 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
709 * the backslashes will be eaten, and the space will act as a
710 * separator. You need to enclose such paths with single quotes, like
711 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
713 * Return value: %TRUE on success, %FALSE if an error was set
716 g_spawn_command_line_sync (const gchar *command_line,
717 gchar **standard_output,
718 gchar **standard_error,
725 g_return_val_if_fail (command_line != NULL, FALSE);
727 if (!g_shell_parse_argv (command_line,
732 retval = g_spawn_sync (NULL,
748 * g_spawn_command_line_async:
749 * @command_line: a command line
750 * @error: return location for errors
752 * A simple version of g_spawn_async() that parses a command line with
753 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
754 * command line in the background. Unlike g_spawn_async(), the
755 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
756 * that %G_SPAWN_SEARCH_PATH can have security implications, so
757 * consider using g_spawn_async() directly if appropriate. Possible
758 * errors are those from g_shell_parse_argv() and g_spawn_async().
760 * The same concerns on Windows apply as for g_spawn_command_line_sync().
762 * Return value: %TRUE on success, %FALSE if error is set.
765 g_spawn_command_line_async (const gchar *command_line,
771 g_return_val_if_fail (command_line != NULL, FALSE);
773 if (!g_shell_parse_argv (command_line,
778 retval = g_spawn_async (NULL,
792 * g_spawn_check_exit_status:
793 * @exit_status: An exit code as returned from g_spawn_sync()
796 * Set @error if @exit_status indicates the child exited abnormally
797 * (e.g. with a nonzero exit code, or via a fatal signal).
799 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
800 * exit status for subprocesses encoded in a platform-specific way.
801 * On Unix, this is guaranteed to be in the same format
802 * <literal>waitpid(2)</literal> returns, and on Windows it is
803 * guaranteed to be the result of
804 * <literal>GetExitCodeProcess()</literal>. Prior to the introduction
805 * of this function in GLib 2.34, interpreting @exit_status required
806 * use of platform-specific APIs, which is problematic for software
807 * using GLib as a cross-platform layer.
809 * Additionally, many programs simply want to determine whether or not
810 * the child exited successfully, and either propagate a #GError or
811 * print a message to standard error. In that common case, this
812 * function can be used. Note that the error message in @error will
813 * contain human-readable information about the exit status.
815 * The <literal>domain</literal> and <literal>code</literal> of @error
816 * have special semantics in the case where the process has an "exit
817 * code", as opposed to being killed by a signal. On Unix, this
818 * happens if <literal>WIFEXITED</literal> would be true of
819 * @exit_status. On Windows, it is always the case.
821 * The special semantics are that the actual exit code will be the
822 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
823 * This allows you to differentiate between different exit codes.
825 * If the process was terminated by some means other than an exit
826 * status, the domain will be %G_SPAWN_ERROR, and the code will be
827 * %G_SPAWN_ERROR_FAILED.
829 * This function just offers convenience; you can of course also check
830 * the available platform via a macro such as %G_OS_UNIX, and use
831 * <literal>WIFEXITED()</literal> and <literal>WEXITSTATUS()</literal>
832 * on @exit_status directly. Do not attempt to scan or parse the
833 * error message string; it may be translated and/or change in future
836 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and @error will be set)
840 g_spawn_check_exit_status (gint exit_status,
843 gboolean ret = FALSE;
845 if (WIFEXITED (exit_status))
847 if (WEXITSTATUS (exit_status) != 0)
849 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
850 _("Child process exited with code %ld"),
851 (long) WEXITSTATUS (exit_status));
855 else if (WIFSIGNALED (exit_status))
857 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
858 _("Child process killed by signal %ld"),
859 (long) WTERMSIG (exit_status));
862 else if (WIFSTOPPED (exit_status))
864 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
865 _("Child process stopped by signal %ld"),
866 (long) WSTOPSIG (exit_status));
871 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
872 _("Child process exited abnormally"));
882 exec_err_to_g_error (gint en)
888 return G_SPAWN_ERROR_ACCES;
894 return G_SPAWN_ERROR_PERM;
900 return G_SPAWN_ERROR_TOO_BIG;
906 return G_SPAWN_ERROR_NOEXEC;
912 return G_SPAWN_ERROR_NAMETOOLONG;
918 return G_SPAWN_ERROR_NOENT;
924 return G_SPAWN_ERROR_NOMEM;
930 return G_SPAWN_ERROR_NOTDIR;
936 return G_SPAWN_ERROR_LOOP;
942 return G_SPAWN_ERROR_TXTBUSY;
948 return G_SPAWN_ERROR_IO;
954 return G_SPAWN_ERROR_NFILE;
960 return G_SPAWN_ERROR_MFILE;
966 return G_SPAWN_ERROR_INVAL;
972 return G_SPAWN_ERROR_ISDIR;
978 return G_SPAWN_ERROR_LIBBAD;
983 return G_SPAWN_ERROR_FAILED;
989 write_all (gint fd, gconstpointer vbuf, gsize to_write)
991 gchar *buf = (gchar *) vbuf;
995 gssize count = write (fd, buf, to_write);
1013 write_err_and_exit (gint fd, gint msg)
1017 write_all (fd, &msg, sizeof(msg));
1018 write_all (fd, &en, sizeof(en));
1024 set_cloexec (void *data, gint fd)
1026 if (fd >= GPOINTER_TO_INT (data))
1027 fcntl (fd, F_SETFD, FD_CLOEXEC);
1034 fdwalk (int (*cb)(void *data, int fd), void *data)
1040 #ifdef HAVE_SYS_RESOURCE_H
1047 if ((d = opendir("/proc/self/fd"))) {
1050 while ((de = readdir(d))) {
1054 if (de->d_name[0] == '.')
1058 l = strtol(de->d_name, &e, 10);
1059 if (errno != 0 || !e || *e)
1064 if ((glong) fd != l)
1070 if ((res = cb (data, fd)) != 0)
1078 /* If /proc is not mounted or not accessible we fall back to the old
1083 #ifdef HAVE_SYS_RESOURCE_H
1085 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1086 open_max = rl.rlim_max;
1089 open_max = sysconf (_SC_OPEN_MAX);
1091 for (fd = 0; fd < open_max; fd++)
1092 if ((res = cb (data, fd)) != 0)
1100 sane_dup2 (gint fd1, gint fd2)
1105 ret = dup2 (fd1, fd2);
1106 if (ret < 0 && errno == EINTR)
1113 sane_open (const char *path, gint mode)
1118 ret = open (path, mode);
1119 if (ret < 0 && errno == EINTR)
1134 do_exec (gint child_err_report_fd,
1138 const gchar *working_directory,
1141 gboolean close_descriptors,
1142 gboolean search_path,
1143 gboolean search_path_from_envp,
1144 gboolean stdout_to_null,
1145 gboolean stderr_to_null,
1146 gboolean child_inherits_stdin,
1147 gboolean file_and_argv_zero,
1148 GSpawnChildSetupFunc child_setup,
1151 if (working_directory && chdir (working_directory) < 0)
1152 write_err_and_exit (child_err_report_fd,
1153 CHILD_CHDIR_FAILED);
1155 /* Close all file descriptors but stdin stdout and stderr as
1156 * soon as we exec. Note that this includes
1157 * child_err_report_fd, which keeps the parent from blocking
1158 * forever on the other end of that pipe.
1160 if (close_descriptors)
1162 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1166 /* We need to do child_err_report_fd anyway */
1167 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1170 /* Redirect pipes as required */
1174 /* dup2 can't actually fail here I don't think */
1176 if (sane_dup2 (stdin_fd, 0) < 0)
1177 write_err_and_exit (child_err_report_fd,
1180 /* ignore this if it doesn't work */
1181 close_and_invalidate (&stdin_fd);
1183 else if (!child_inherits_stdin)
1185 /* Keep process from blocking on a read of stdin */
1186 gint read_null = open ("/dev/null", O_RDONLY);
1187 g_assert (read_null != -1);
1188 sane_dup2 (read_null, 0);
1189 close_and_invalidate (&read_null);
1194 /* dup2 can't actually fail here I don't think */
1196 if (sane_dup2 (stdout_fd, 1) < 0)
1197 write_err_and_exit (child_err_report_fd,
1200 /* ignore this if it doesn't work */
1201 close_and_invalidate (&stdout_fd);
1203 else if (stdout_to_null)
1205 gint write_null = sane_open ("/dev/null", O_WRONLY);
1206 g_assert (write_null != -1);
1207 sane_dup2 (write_null, 1);
1208 close_and_invalidate (&write_null);
1213 /* dup2 can't actually fail here I don't think */
1215 if (sane_dup2 (stderr_fd, 2) < 0)
1216 write_err_and_exit (child_err_report_fd,
1219 /* ignore this if it doesn't work */
1220 close_and_invalidate (&stderr_fd);
1222 else if (stderr_to_null)
1224 gint write_null = sane_open ("/dev/null", O_WRONLY);
1225 sane_dup2 (write_null, 2);
1226 close_and_invalidate (&write_null);
1229 /* Call user function just before we exec */
1232 (* child_setup) (user_data);
1236 file_and_argv_zero ? argv + 1 : argv,
1237 envp, search_path, search_path_from_envp);
1240 write_err_and_exit (child_err_report_fd,
1257 if (bytes >= sizeof(gint)*2)
1258 break; /* give up, who knows what happened, should not be
1264 ((gchar*)buf) + bytes,
1265 sizeof(gint) * n_ints_in_buf - bytes);
1266 if (chunk < 0 && errno == EINTR)
1273 /* Some weird shit happened, bail out */
1276 G_SPAWN_ERROR_FAILED,
1277 _("Failed to read from child pipe (%s)"),
1278 g_strerror (errsv));
1282 else if (chunk == 0)
1284 else /* chunk > 0 */
1288 *n_ints_read = (gint)(bytes / sizeof(gint));
1294 fork_exec_with_pipes (gboolean intermediate_child,
1295 const gchar *working_directory,
1298 gboolean close_descriptors,
1299 gboolean search_path,
1300 gboolean search_path_from_envp,
1301 gboolean stdout_to_null,
1302 gboolean stderr_to_null,
1303 gboolean child_inherits_stdin,
1304 gboolean file_and_argv_zero,
1305 gboolean cloexec_pipes,
1306 GSpawnChildSetupFunc child_setup,
1309 gint *standard_input,
1310 gint *standard_output,
1311 gint *standard_error,
1315 gint stdin_pipe[2] = { -1, -1 };
1316 gint stdout_pipe[2] = { -1, -1 };
1317 gint stderr_pipe[2] = { -1, -1 };
1318 gint child_err_report_pipe[2] = { -1, -1 };
1319 gint child_pid_report_pipe[2] = { -1, -1 };
1320 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1323 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1326 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1327 goto cleanup_and_fail;
1329 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1330 goto cleanup_and_fail;
1332 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1333 goto cleanup_and_fail;
1335 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1336 goto cleanup_and_fail;
1347 _("Failed to fork (%s)"),
1348 g_strerror (errsv));
1350 goto cleanup_and_fail;
1354 /* Immediate child. This may or may not be the child that
1355 * actually execs the new process.
1358 /* Reset some signal handlers that we may use */
1359 signal (SIGCHLD, SIG_DFL);
1360 signal (SIGINT, SIG_DFL);
1361 signal (SIGTERM, SIG_DFL);
1362 signal (SIGHUP, SIG_DFL);
1364 /* Be sure we crash if the parent exits
1365 * and we write to the err_report_pipe
1367 signal (SIGPIPE, SIG_DFL);
1369 /* Close the parent's end of the pipes;
1370 * not needed in the close_descriptors case,
1373 close_and_invalidate (&child_err_report_pipe[0]);
1374 close_and_invalidate (&child_pid_report_pipe[0]);
1375 close_and_invalidate (&stdin_pipe[1]);
1376 close_and_invalidate (&stdout_pipe[0]);
1377 close_and_invalidate (&stderr_pipe[0]);
1379 if (intermediate_child)
1381 /* We need to fork an intermediate child that launches the
1382 * final child. The purpose of the intermediate child
1383 * is to exit, so we can waitpid() it immediately.
1384 * Then the grandchild will not become a zombie.
1386 GPid grandchild_pid;
1388 grandchild_pid = fork ();
1390 if (grandchild_pid < 0)
1392 /* report -1 as child PID */
1393 write_all (child_pid_report_pipe[1], &grandchild_pid,
1394 sizeof(grandchild_pid));
1396 write_err_and_exit (child_err_report_pipe[1],
1399 else if (grandchild_pid == 0)
1401 close_and_invalidate (&child_pid_report_pipe[1]);
1402 do_exec (child_err_report_pipe[1],
1411 search_path_from_envp,
1414 child_inherits_stdin,
1421 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1422 close_and_invalidate (&child_pid_report_pipe[1]);
1429 /* Just run the child.
1432 do_exec (child_err_report_pipe[1],
1441 search_path_from_envp,
1444 child_inherits_stdin,
1457 /* Close the uncared-about ends of the pipes */
1458 close_and_invalidate (&child_err_report_pipe[1]);
1459 close_and_invalidate (&child_pid_report_pipe[1]);
1460 close_and_invalidate (&stdin_pipe[0]);
1461 close_and_invalidate (&stdout_pipe[1]);
1462 close_and_invalidate (&stderr_pipe[1]);
1464 /* If we had an intermediate child, reap it */
1465 if (intermediate_child)
1468 if (waitpid (pid, &status, 0) < 0)
1472 else if (errno == ECHILD)
1473 ; /* do nothing, child already reaped */
1475 g_warning ("waitpid() should not fail in "
1476 "'fork_exec_with_pipes'");
1481 if (!read_ints (child_err_report_pipe[0],
1484 goto cleanup_and_fail;
1488 /* Error from the child. */
1492 case CHILD_CHDIR_FAILED:
1495 G_SPAWN_ERROR_CHDIR,
1496 _("Failed to change to directory '%s' (%s)"),
1498 g_strerror (buf[1]));
1502 case CHILD_EXEC_FAILED:
1505 exec_err_to_g_error (buf[1]),
1506 _("Failed to execute child process \"%s\" (%s)"),
1508 g_strerror (buf[1]));
1512 case CHILD_DUP2_FAILED:
1515 G_SPAWN_ERROR_FAILED,
1516 _("Failed to redirect output or input of child process (%s)"),
1517 g_strerror (buf[1]));
1521 case CHILD_FORK_FAILED:
1525 _("Failed to fork child process (%s)"),
1526 g_strerror (buf[1]));
1532 G_SPAWN_ERROR_FAILED,
1533 _("Unknown error executing child process \"%s\""),
1538 goto cleanup_and_fail;
1541 /* Get child pid from intermediate child pipe. */
1542 if (intermediate_child)
1546 if (!read_ints (child_pid_report_pipe[0],
1547 buf, 1, &n_ints, error))
1548 goto cleanup_and_fail;
1556 G_SPAWN_ERROR_FAILED,
1557 _("Failed to read enough data from child pid pipe (%s)"),
1558 g_strerror (errsv));
1559 goto cleanup_and_fail;
1563 /* we have the child pid */
1568 /* Success against all odds! return the information */
1569 close_and_invalidate (&child_err_report_pipe[0]);
1570 close_and_invalidate (&child_pid_report_pipe[0]);
1576 *standard_input = stdin_pipe[1];
1577 if (standard_output)
1578 *standard_output = stdout_pipe[0];
1580 *standard_error = stderr_pipe[0];
1587 /* There was an error from the Child, reap the child to avoid it being
1594 if (waitpid (pid, NULL, 0) < 0)
1598 else if (errno == ECHILD)
1599 ; /* do nothing, child already reaped */
1601 g_warning ("waitpid() should not fail in "
1602 "'fork_exec_with_pipes'");
1606 close_and_invalidate (&child_err_report_pipe[0]);
1607 close_and_invalidate (&child_err_report_pipe[1]);
1608 close_and_invalidate (&child_pid_report_pipe[0]);
1609 close_and_invalidate (&child_pid_report_pipe[1]);
1610 close_and_invalidate (&stdin_pipe[0]);
1611 close_and_invalidate (&stdin_pipe[1]);
1612 close_and_invalidate (&stdout_pipe[0]);
1613 close_and_invalidate (&stdout_pipe[1]);
1614 close_and_invalidate (&stderr_pipe[0]);
1615 close_and_invalidate (&stderr_pipe[1]);
1620 /* Based on execvp from GNU C Library */
1623 script_execute (const gchar *file,
1627 /* Count the arguments. */
1632 /* Construct an argument list for the shell. */
1636 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1638 new_argv[0] = (char *) "/bin/sh";
1639 new_argv[1] = (char *) file;
1642 new_argv[argc + 1] = argv[argc];
1646 /* Execute the shell. */
1648 execve (new_argv[0], new_argv, envp);
1650 execv (new_argv[0], new_argv);
1657 my_strchrnul (const gchar *str, gchar c)
1659 gchar *p = (gchar*) str;
1660 while (*p && (*p != c))
1667 g_execute (const gchar *file,
1670 gboolean search_path,
1671 gboolean search_path_from_envp)
1675 /* We check the simple case first. */
1680 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1682 /* Don't search when it contains a slash. */
1684 execve (file, argv, envp);
1688 if (errno == ENOEXEC)
1689 script_execute (file, argv, envp);
1693 gboolean got_eacces = 0;
1694 const gchar *path, *p;
1695 gchar *name, *freeme;
1700 if (search_path_from_envp)
1701 path = g_environ_getenv (envp, "PATH");
1702 if (search_path && path == NULL)
1703 path = g_getenv ("PATH");
1707 /* There is no 'PATH' in the environment. The default
1708 * search path in libc is the current directory followed by
1709 * the path 'confstr' returns for '_CS_PATH'.
1712 /* In GLib we put . last, for security, and don't use the
1713 * unportable confstr(); UNIX98 does not actually specify
1714 * what to search if PATH is unset. POSIX may, dunno.
1717 path = "/bin:/usr/bin:.";
1720 len = strlen (file) + 1;
1721 pathlen = strlen (path);
1722 freeme = name = g_malloc (pathlen + len + 1);
1724 /* Copy the file name at the top, including '\0' */
1725 memcpy (name + pathlen + 1, file, len);
1726 name = name + pathlen;
1727 /* And add the slash before the filename */
1736 p = my_strchrnul (path, ':');
1739 /* Two adjacent colons, or a colon at the beginning or the end
1740 * of 'PATH' means to search the current directory.
1744 startp = memcpy (name - (p - path), path, p - path);
1746 /* Try to execute this name. If it works, execv will not return. */
1748 execve (startp, argv, envp);
1750 execv (startp, argv);
1752 if (errno == ENOEXEC)
1753 script_execute (startp, argv, envp);
1758 /* Record the we got a 'Permission denied' error. If we end
1759 * up finding no executable we can use, we want to diagnose
1760 * that we did find one but were denied access.
1773 /* Those errors indicate the file is missing or not executable
1774 * by us, in which case we want to just try the next path
1781 /* Some strange filesystems like AFS return even
1782 * stranger error numbers. They cannot reasonably mean anything
1783 * else so ignore those, too.
1788 /* Some other error means we found an executable file, but
1789 * something went wrong executing it; return the error to our
1796 while (*p++ != '\0');
1798 /* We tried every element and none of them worked. */
1800 /* At least one failure was due to permissions, so report that
1808 /* Return the error from the last attempt (probably ENOENT). */
1813 * g_spawn_close_pid:
1814 * @pid: The process reference to close
1816 * On some platforms, notably Windows, the #GPid type represents a resource
1817 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1818 * is provided for this purpose. It should be used on all platforms, even
1819 * though it doesn't do anything under UNIX.
1822 g_spawn_close_pid (GPid pid)