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
63 * GLib supports spawning of processes with an API that is more
64 * convenient than the bare UNIX fork() and exec().
66 * The g_spawn family of functions has synchronous (g_spawn_sync())
67 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
68 * as well as convenience variants that take a complete shell-like
69 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
71 * See #GSubprocess in GIO for a higher-level API that provides
72 * stream interfaces for communication with child processes.
77 static gint
g_execute (const gchar
*file
,
81 gboolean search_path_from_envp
);
83 static gboolean
fork_exec_with_pipes (gboolean intermediate_child
,
84 const gchar
*working_directory
,
87 gboolean close_descriptors
,
89 gboolean search_path_from_envp
,
90 gboolean stdout_to_null
,
91 gboolean stderr_to_null
,
92 gboolean child_inherits_stdin
,
93 gboolean file_and_argv_zero
,
94 gboolean cloexec_pipes
,
95 GSpawnChildSetupFunc child_setup
,
99 gint
*standard_output
,
100 gint
*standard_error
,
103 G_DEFINE_QUARK (g
-exec
-error
-quark
, g_spawn_error
)
104 G_DEFINE_QUARK (g
-spawn
-exit
-error
-quark
, g_spawn_exit_error
)
108 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
109 * @argv: (array zero-terminated=1): child's argument vector
110 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
111 * @flags: flags from #GSpawnFlags
112 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
113 * @user_data: (closure): user data for @child_setup
114 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
115 * @error: return location for error
117 * See g_spawn_async_with_pipes() for a full description; this function
118 * simply calls the g_spawn_async_with_pipes() without any pipes.
120 * You should call g_spawn_close_pid() on the returned child process
121 * reference when you don't need it any more.
123 * If you are writing a GTK+ application, and the program you are
124 * spawning is a graphical application, too, then you may want to
125 * use gdk_spawn_on_screen() instead to ensure that the spawned program
126 * opens its windows on the right screen.
128 * Note that the returned @child_pid on Windows is a handle to the child
129 * process and not its identifier. Process handles and process identifiers
130 * are different concepts on Windows.
132 * Returns: %TRUE on success, %FALSE if error is set
135 g_spawn_async (const gchar
*working_directory
,
139 GSpawnChildSetupFunc child_setup
,
144 g_return_val_if_fail (argv
!= NULL
, FALSE
);
146 return g_spawn_async_with_pipes (working_directory
,
156 /* Avoids a danger in threaded situations (calling close()
157 * on a file descriptor twice, and another thread has
158 * re-opened it since the first close)
161 close_and_invalidate (gint
*fd
)
167 (void) g_close (*fd
, NULL
);
172 /* Some versions of OS X define READ_OK in public headers */
177 READ_FAILED
= 0, /* FALSE */
183 read_data (GString
*str
,
191 bytes
= read (fd
, buf
, 4096);
197 g_string_append_len (str
, buf
, bytes
);
200 else if (errno
== EINTR
)
209 _("Failed to read data from child process (%s)"),
218 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
219 * @argv: (array zero-terminated=1): child's argument vector
220 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
221 * @flags: flags from #GSpawnFlags
222 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
223 * @user_data: (closure): user data for @child_setup
224 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
225 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
226 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
227 * @error: return location for error, or %NULL
229 * Executes a child synchronously (waits for the child to exit before returning).
230 * All output from the child is stored in @standard_output and @standard_error,
231 * if those parameters are non-%NULL. Note that you must set the
232 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
233 * passing %NULL for @standard_output and @standard_error.
235 * If @exit_status is non-%NULL, the platform-specific exit status of
236 * the child is stored there; see the documentation of
237 * g_spawn_check_exit_status() for how to use and interpret this.
238 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
241 * If an error occurs, no data is returned in @standard_output,
242 * @standard_error, or @exit_status.
244 * This function calls g_spawn_async_with_pipes() internally; see that
245 * function for full details on the other parameters and details on
246 * how these functions work on Windows.
248 * Returns: %TRUE on success, %FALSE if an error was set
251 g_spawn_sync (const gchar
*working_directory
,
255 GSpawnChildSetupFunc child_setup
,
257 gchar
**standard_output
,
258 gchar
**standard_error
,
267 GString
*outstr
= NULL
;
268 GString
*errstr
= NULL
;
272 g_return_val_if_fail (argv
!= NULL
, FALSE
);
273 g_return_val_if_fail (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
), FALSE
);
274 g_return_val_if_fail (standard_output
== NULL
||
275 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
276 g_return_val_if_fail (standard_error
== NULL
||
277 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
279 /* Just to ensure segfaults if callers try to use
280 * these when an error is reported.
283 *standard_output
= NULL
;
286 *standard_error
= NULL
;
288 if (!fork_exec_with_pipes (FALSE
,
292 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
293 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
294 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
295 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
296 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
297 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
298 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
299 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
304 standard_output
? &outpipe
: NULL
,
305 standard_error
? &errpipe
: NULL
,
309 /* Read data from child. */
315 outstr
= g_string_new (NULL
);
320 errstr
= g_string_new (NULL
);
323 /* Read data until we get EOF on both pipes. */
332 FD_SET (outpipe
, &fds
);
334 FD_SET (errpipe
, &fds
);
336 ret
= select (MAX (outpipe
, errpipe
) + 1,
339 NULL
/* no timeout */);
353 _("Unexpected error in select() reading data from a child process (%s)"),
359 if (outpipe
>= 0 && FD_ISSET (outpipe
, &fds
))
361 switch (read_data (outstr
, outpipe
, error
))
367 close_and_invalidate (&outpipe
);
378 if (errpipe
>= 0 && FD_ISSET (errpipe
, &fds
))
380 switch (read_data (errstr
, errpipe
, error
))
386 close_and_invalidate (&errpipe
);
398 /* These should only be open still if we had an error. */
401 close_and_invalidate (&outpipe
);
403 close_and_invalidate (&errpipe
);
405 /* Wait for child to exit, even if we have
410 ret
= waitpid (pid
, &status
, 0);
416 else if (errno
== ECHILD
)
420 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.");
424 /* We don't need the exit status. */
429 if (!failed
) /* avoid error pileups */
438 _("Unexpected error in waitpid() (%s)"),
447 g_string_free (outstr
, TRUE
);
449 g_string_free (errstr
, TRUE
);
456 *exit_status
= status
;
459 *standard_output
= g_string_free (outstr
, FALSE
);
462 *standard_error
= g_string_free (errstr
, FALSE
);
469 * g_spawn_async_with_pipes:
470 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
471 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
472 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
473 * @flags: flags from #GSpawnFlags
474 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
475 * @user_data: (closure): user data for @child_setup
476 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
477 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
478 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
479 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
480 * @error: return location for error
482 * Executes a child program asynchronously (your program will not
483 * block waiting for the child to exit). The child program is
484 * specified by the only argument that must be provided, @argv.
485 * @argv should be a %NULL-terminated array of strings, to be passed
486 * as the argument vector for the child. The first string in @argv
487 * is of course the name of the program to execute. By default, the
488 * name of the program must be a full path. If @flags contains the
489 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
490 * used to search for the executable. If @flags contains the
491 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
492 * @envp is used to search for the executable. If both the
493 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
494 * are set, the `PATH` variable from @envp takes precedence over
495 * the environment variable.
497 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
498 * used, then the program will be run from the current directory (or
499 * @working_directory, if specified); this might be unexpected or even
500 * dangerous in some cases when the current directory is world-writable.
502 * On Windows, note that all the string or string vector arguments to
503 * this function and the other g_spawn*() functions are in UTF-8, the
504 * GLib file name encoding. Unicode characters that are not part of
505 * the system codepage passed in these arguments will be correctly
506 * available in the spawned program only if it uses wide character API
507 * to retrieve its command line. For C programs built with Microsoft's
508 * tools it is enough to make the program have a wmain() instead of
509 * main(). wmain() has a wide character argument vector as parameter.
511 * At least currently, mingw doesn't support wmain(), so if you use
512 * mingw to develop the spawned program, it should call
513 * g_win32_get_command_line() to get arguments in UTF-8.
515 * On Windows the low-level child process creation API CreateProcess()
516 * doesn't use argument vectors, but a command line. The C runtime
517 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
518 * eventually calls) paste the argument vector elements together into
519 * a command line, and the C runtime startup code does a corresponding
520 * reconstruction of an argument vector from the command line, to be
521 * passed to main(). Complications arise when you have argument vector
522 * elements that contain spaces of double quotes. The spawn*() functions
523 * don't do any quoting or escaping, but on the other hand the startup
524 * code does do unquoting and unescaping in order to enable receiving
525 * arguments with embedded spaces or double quotes. To work around this
526 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
527 * argument vector elements that need it before calling the C runtime
530 * The returned @child_pid on Windows is a handle to the child
531 * process, not its identifier. Process handles and process
532 * identifiers are different concepts on Windows.
534 * @envp is a %NULL-terminated array of strings, where each string
535 * has the form `KEY=VALUE`. This will become the child's environment.
536 * If @envp is %NULL, the child inherits its 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 %SIGCHLD 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 descriptors
551 * except stdin/stdout/stderr will be closed before calling exec() in
552 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
553 * absolute path, it will be looked for in the `PATH` environment
554 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
555 * absolute path, it will be looked for in the `PATH` variable from
556 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
557 * are used, the value from @envp takes precedence over the environment.
558 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
559 * will be discarded, instead of going to the same location as the parent's
560 * standard output. If you use this flag, @standard_output must be %NULL.
561 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
562 * will be discarded, instead of going to the same location as the parent's
563 * standard error. If you use this flag, @standard_error must be %NULL.
564 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
565 * standard input (by default, the child's standard input is attached to
566 * /dev/null). If you use this flag, @standard_input must be %NULL.
567 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
568 * the file to execute, while the remaining elements are the actual
569 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
570 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
572 * @child_setup and @user_data are a function and user data. On POSIX
573 * platforms, the function is called in the child after GLib has
574 * performed all the setup it plans to perform (including creating
575 * pipes, closing file descriptors, etc.) but before calling exec().
576 * That is, @child_setup is called just before calling exec() in the
577 * child. Obviously actions taken in this function will only affect
578 * the child, not the parent.
580 * On Windows, there is no separate fork() and exec() functionality.
581 * Child processes are created and run with a single API call,
582 * CreateProcess(). There is no sensible thing @child_setup
583 * could be used for on Windows so it is ignored and not called.
585 * If non-%NULL, @child_pid will on Unix be filled with the child's
586 * process ID. You can use the process ID to send signals to the child,
587 * or to use g_child_watch_add() (or waitpid()) if you specified the
588 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
589 * filled with a handle to the child process only if you specified the
590 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
591 * process using the Win32 API, for example wait for its termination
592 * with the WaitFor*() functions, or examine its exit code with
593 * GetExitCodeProcess(). You should close the handle with CloseHandle()
594 * or g_spawn_close_pid() when you no longer need it.
596 * If non-%NULL, the @standard_input, @standard_output, @standard_error
597 * locations will be filled with file descriptors for writing to the child's
598 * standard input or reading from its standard output or standard error.
599 * The caller of g_spawn_async_with_pipes() must close these file descriptors
600 * when they are no longer in use. If these parameters are %NULL, the
601 * corresponding pipe won't be created.
603 * If @standard_input is NULL, the child's standard input is attached to
604 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
606 * If @standard_error is NULL, the child's standard error goes to the same
607 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
610 * If @standard_output is NULL, the child's standard output goes to the same
611 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
614 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
615 * If an error is set, the function returns %FALSE. Errors are reported
616 * even if they occur in the child (for example if the executable in
617 * @argv[0] is not found). Typically the `message` field of returned
618 * errors should be displayed to users. Possible errors are those from
619 * the #G_SPAWN_ERROR domain.
621 * If an error occurs, @child_pid, @standard_input, @standard_output,
622 * and @standard_error will not be filled with valid values.
624 * If @child_pid is not %NULL and an error does not occur then the returned
625 * process reference must be closed using g_spawn_close_pid().
627 * If you are writing a GTK+ application, and the program you
628 * are spawning is a graphical application, too, then you may
629 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
630 * the spawned program opens its windows on the right screen.
632 * Returns: %TRUE on success, %FALSE if an error was set
635 g_spawn_async_with_pipes (const gchar
*working_directory
,
639 GSpawnChildSetupFunc child_setup
,
642 gint
*standard_input
,
643 gint
*standard_output
,
644 gint
*standard_error
,
647 g_return_val_if_fail (argv
!= NULL
, FALSE
);
648 g_return_val_if_fail (standard_output
== NULL
||
649 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
650 g_return_val_if_fail (standard_error
== NULL
||
651 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
652 /* can't inherit stdin if we have an input pipe. */
653 g_return_val_if_fail (standard_input
== NULL
||
654 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
656 return fork_exec_with_pipes (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
660 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
661 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
662 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
663 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
664 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
665 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
666 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
667 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
678 * g_spawn_command_line_sync:
679 * @command_line: a command line
680 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
681 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
682 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
683 * @error: return location for errors
685 * A simple version of g_spawn_sync() with little-used parameters
686 * removed, taking a command line instead of an argument vector. See
687 * g_spawn_sync() for full details. @command_line will be parsed by
688 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
689 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
690 * implications, so consider using g_spawn_sync() directly if
691 * appropriate. Possible errors are those from g_spawn_sync() and those
692 * from g_shell_parse_argv().
694 * If @exit_status is non-%NULL, the platform-specific exit status of
695 * the child is stored there; see the documentation of
696 * g_spawn_check_exit_status() for how to use and interpret this.
698 * On Windows, please note the implications of g_shell_parse_argv()
699 * parsing @command_line. Parsing is done according to Unix shell rules, not
700 * Windows command interpreter rules.
701 * Space is a separator, and backslashes are
702 * special. Thus you cannot simply pass a @command_line containing
703 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
704 * the backslashes will be eaten, and the space will act as a
705 * separator. You need to enclose such paths with single quotes, like
706 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
708 * Returns: %TRUE on success, %FALSE if an error was set
711 g_spawn_command_line_sync (const gchar
*command_line
,
712 gchar
**standard_output
,
713 gchar
**standard_error
,
720 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
722 if (!g_shell_parse_argv (command_line
,
727 retval
= g_spawn_sync (NULL
,
743 * g_spawn_command_line_async:
744 * @command_line: a command line
745 * @error: return location for errors
747 * A simple version of g_spawn_async() that parses a command line with
748 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
749 * command line in the background. Unlike g_spawn_async(), the
750 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
751 * that %G_SPAWN_SEARCH_PATH can have security implications, so
752 * consider using g_spawn_async() directly if appropriate. Possible
753 * errors are those from g_shell_parse_argv() and g_spawn_async().
755 * The same concerns on Windows apply as for g_spawn_command_line_sync().
757 * Returns: %TRUE on success, %FALSE if error is set
760 g_spawn_command_line_async (const gchar
*command_line
,
766 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
768 if (!g_shell_parse_argv (command_line
,
773 retval
= g_spawn_async (NULL
,
787 * g_spawn_check_exit_status:
788 * @exit_status: An exit code as returned from g_spawn_sync()
791 * Set @error if @exit_status indicates the child exited abnormally
792 * (e.g. with a nonzero exit code, or via a fatal signal).
794 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
795 * exit status for subprocesses encoded in a platform-specific way.
796 * On Unix, this is guaranteed to be in the same format waitpid() returns,
797 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
799 * Prior to the introduction of this function in GLib 2.34, interpreting
800 * @exit_status required use of platform-specific APIs, which is problematic
801 * for software using GLib as a cross-platform layer.
803 * Additionally, many programs simply want to determine whether or not
804 * the child exited successfully, and either propagate a #GError or
805 * print a message to standard error. In that common case, this function
806 * can be used. Note that the error message in @error will contain
807 * human-readable information about the exit status.
809 * The @domain and @code of @error have special semantics in the case
810 * where the process has an "exit code", as opposed to being killed by
811 * a signal. On Unix, this happens if WIFEXITED() would be true of
812 * @exit_status. On Windows, it is always the case.
814 * The special semantics are that the actual exit code will be the
815 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
816 * This allows you to differentiate between different exit codes.
818 * If the process was terminated by some means other than an exit
819 * status, the domain will be %G_SPAWN_ERROR, and the code will be
820 * %G_SPAWN_ERROR_FAILED.
822 * This function just offers convenience; you can of course also check
823 * the available platform via a macro such as %G_OS_UNIX, and use
824 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
825 * to scan or parse the error message string; it may be translated and/or
826 * change in future versions of GLib.
828 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
829 * @error will be set)
834 g_spawn_check_exit_status (gint exit_status
,
837 gboolean ret
= FALSE
;
839 if (WIFEXITED (exit_status
))
841 if (WEXITSTATUS (exit_status
) != 0)
843 g_set_error (error
, G_SPAWN_EXIT_ERROR
, WEXITSTATUS (exit_status
),
844 _("Child process exited with code %ld"),
845 (long) WEXITSTATUS (exit_status
));
849 else if (WIFSIGNALED (exit_status
))
851 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
852 _("Child process killed by signal %ld"),
853 (long) WTERMSIG (exit_status
));
856 else if (WIFSTOPPED (exit_status
))
858 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
859 _("Child process stopped by signal %ld"),
860 (long) WSTOPSIG (exit_status
));
865 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
866 _("Child process exited abnormally"));
876 exec_err_to_g_error (gint en
)
882 return G_SPAWN_ERROR_ACCES
;
888 return G_SPAWN_ERROR_PERM
;
894 return G_SPAWN_ERROR_TOO_BIG
;
900 return G_SPAWN_ERROR_NOEXEC
;
906 return G_SPAWN_ERROR_NAMETOOLONG
;
912 return G_SPAWN_ERROR_NOENT
;
918 return G_SPAWN_ERROR_NOMEM
;
924 return G_SPAWN_ERROR_NOTDIR
;
930 return G_SPAWN_ERROR_LOOP
;
936 return G_SPAWN_ERROR_TXTBUSY
;
942 return G_SPAWN_ERROR_IO
;
948 return G_SPAWN_ERROR_NFILE
;
954 return G_SPAWN_ERROR_MFILE
;
960 return G_SPAWN_ERROR_INVAL
;
966 return G_SPAWN_ERROR_ISDIR
;
972 return G_SPAWN_ERROR_LIBBAD
;
977 return G_SPAWN_ERROR_FAILED
;
983 write_all (gint fd
, gconstpointer vbuf
, gsize to_write
)
985 gchar
*buf
= (gchar
*) vbuf
;
989 gssize count
= write (fd
, buf
, to_write
);
1007 write_err_and_exit (gint fd
, gint msg
)
1011 write_all (fd
, &msg
, sizeof(msg
));
1012 write_all (fd
, &en
, sizeof(en
));
1018 set_cloexec (void *data
, gint fd
)
1020 if (fd
>= GPOINTER_TO_INT (data
))
1021 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
1028 fdwalk (int (*cb
)(void *data
, int fd
), void *data
)
1034 #ifdef HAVE_SYS_RESOURCE_H
1041 if ((d
= opendir("/proc/self/fd"))) {
1044 while ((de
= readdir(d
))) {
1048 if (de
->d_name
[0] == '.')
1052 l
= strtol(de
->d_name
, &e
, 10);
1053 if (errno
!= 0 || !e
|| *e
)
1058 if ((glong
) fd
!= l
)
1064 if ((res
= cb (data
, fd
)) != 0)
1072 /* If /proc is not mounted or not accessible we fall back to the old
1077 #ifdef HAVE_SYS_RESOURCE_H
1079 if (getrlimit(RLIMIT_NOFILE
, &rl
) == 0 && rl
.rlim_max
!= RLIM_INFINITY
)
1080 open_max
= rl
.rlim_max
;
1083 open_max
= sysconf (_SC_OPEN_MAX
);
1085 for (fd
= 0; fd
< open_max
; fd
++)
1086 if ((res
= cb (data
, fd
)) != 0)
1094 sane_dup2 (gint fd1
, gint fd2
)
1099 ret
= dup2 (fd1
, fd2
);
1100 if (ret
< 0 && errno
== EINTR
)
1107 sane_open (const char *path
, gint mode
)
1112 ret
= open (path
, mode
);
1113 if (ret
< 0 && errno
== EINTR
)
1128 do_exec (gint child_err_report_fd
,
1132 const gchar
*working_directory
,
1135 gboolean close_descriptors
,
1136 gboolean search_path
,
1137 gboolean search_path_from_envp
,
1138 gboolean stdout_to_null
,
1139 gboolean stderr_to_null
,
1140 gboolean child_inherits_stdin
,
1141 gboolean file_and_argv_zero
,
1142 GSpawnChildSetupFunc child_setup
,
1145 if (working_directory
&& chdir (working_directory
) < 0)
1146 write_err_and_exit (child_err_report_fd
,
1147 CHILD_CHDIR_FAILED
);
1149 /* Close all file descriptors but stdin stdout and stderr as
1150 * soon as we exec. Note that this includes
1151 * child_err_report_fd, which keeps the parent from blocking
1152 * forever on the other end of that pipe.
1154 if (close_descriptors
)
1156 fdwalk (set_cloexec
, GINT_TO_POINTER(3));
1160 /* We need to do child_err_report_fd anyway */
1161 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd
);
1164 /* Redirect pipes as required */
1168 /* dup2 can't actually fail here I don't think */
1170 if (sane_dup2 (stdin_fd
, 0) < 0)
1171 write_err_and_exit (child_err_report_fd
,
1174 /* ignore this if it doesn't work */
1175 close_and_invalidate (&stdin_fd
);
1177 else if (!child_inherits_stdin
)
1179 /* Keep process from blocking on a read of stdin */
1180 gint read_null
= open ("/dev/null", O_RDONLY
);
1181 g_assert (read_null
!= -1);
1182 sane_dup2 (read_null
, 0);
1183 close_and_invalidate (&read_null
);
1188 /* dup2 can't actually fail here I don't think */
1190 if (sane_dup2 (stdout_fd
, 1) < 0)
1191 write_err_and_exit (child_err_report_fd
,
1194 /* ignore this if it doesn't work */
1195 close_and_invalidate (&stdout_fd
);
1197 else if (stdout_to_null
)
1199 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1200 g_assert (write_null
!= -1);
1201 sane_dup2 (write_null
, 1);
1202 close_and_invalidate (&write_null
);
1207 /* dup2 can't actually fail here I don't think */
1209 if (sane_dup2 (stderr_fd
, 2) < 0)
1210 write_err_and_exit (child_err_report_fd
,
1213 /* ignore this if it doesn't work */
1214 close_and_invalidate (&stderr_fd
);
1216 else if (stderr_to_null
)
1218 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1219 sane_dup2 (write_null
, 2);
1220 close_and_invalidate (&write_null
);
1223 /* Call user function just before we exec */
1226 (* child_setup
) (user_data
);
1230 file_and_argv_zero
? argv
+ 1 : argv
,
1231 envp
, search_path
, search_path_from_envp
);
1234 write_err_and_exit (child_err_report_fd
,
1251 if (bytes
>= sizeof(gint
)*2)
1252 break; /* give up, who knows what happened, should not be
1258 ((gchar
*)buf
) + bytes
,
1259 sizeof(gint
) * n_ints_in_buf
- bytes
);
1260 if (chunk
< 0 && errno
== EINTR
)
1267 /* Some weird shit happened, bail out */
1270 G_SPAWN_ERROR_FAILED
,
1271 _("Failed to read from child pipe (%s)"),
1272 g_strerror (errsv
));
1276 else if (chunk
== 0)
1278 else /* chunk > 0 */
1282 *n_ints_read
= (gint
)(bytes
/ sizeof(gint
));
1288 fork_exec_with_pipes (gboolean intermediate_child
,
1289 const gchar
*working_directory
,
1292 gboolean close_descriptors
,
1293 gboolean search_path
,
1294 gboolean search_path_from_envp
,
1295 gboolean stdout_to_null
,
1296 gboolean stderr_to_null
,
1297 gboolean child_inherits_stdin
,
1298 gboolean file_and_argv_zero
,
1299 gboolean cloexec_pipes
,
1300 GSpawnChildSetupFunc child_setup
,
1303 gint
*standard_input
,
1304 gint
*standard_output
,
1305 gint
*standard_error
,
1309 gint stdin_pipe
[2] = { -1, -1 };
1310 gint stdout_pipe
[2] = { -1, -1 };
1311 gint stderr_pipe
[2] = { -1, -1 };
1312 gint child_err_report_pipe
[2] = { -1, -1 };
1313 gint child_pid_report_pipe
[2] = { -1, -1 };
1314 guint pipe_flags
= cloexec_pipes
? FD_CLOEXEC
: 0;
1317 if (!g_unix_open_pipe (child_err_report_pipe
, pipe_flags
, error
))
1320 if (intermediate_child
&& !g_unix_open_pipe (child_pid_report_pipe
, pipe_flags
, error
))
1321 goto cleanup_and_fail
;
1323 if (standard_input
&& !g_unix_open_pipe (stdin_pipe
, pipe_flags
, error
))
1324 goto cleanup_and_fail
;
1326 if (standard_output
&& !g_unix_open_pipe (stdout_pipe
, pipe_flags
, error
))
1327 goto cleanup_and_fail
;
1329 if (standard_error
&& !g_unix_open_pipe (stderr_pipe
, FD_CLOEXEC
, error
))
1330 goto cleanup_and_fail
;
1341 _("Failed to fork (%s)"),
1342 g_strerror (errsv
));
1344 goto cleanup_and_fail
;
1348 /* Immediate child. This may or may not be the child that
1349 * actually execs the new process.
1352 /* Reset some signal handlers that we may use */
1353 signal (SIGCHLD
, SIG_DFL
);
1354 signal (SIGINT
, SIG_DFL
);
1355 signal (SIGTERM
, SIG_DFL
);
1356 signal (SIGHUP
, SIG_DFL
);
1358 /* Be sure we crash if the parent exits
1359 * and we write to the err_report_pipe
1361 signal (SIGPIPE
, SIG_DFL
);
1363 /* Close the parent's end of the pipes;
1364 * not needed in the close_descriptors case,
1367 close_and_invalidate (&child_err_report_pipe
[0]);
1368 close_and_invalidate (&child_pid_report_pipe
[0]);
1369 close_and_invalidate (&stdin_pipe
[1]);
1370 close_and_invalidate (&stdout_pipe
[0]);
1371 close_and_invalidate (&stderr_pipe
[0]);
1373 if (intermediate_child
)
1375 /* We need to fork an intermediate child that launches the
1376 * final child. The purpose of the intermediate child
1377 * is to exit, so we can waitpid() it immediately.
1378 * Then the grandchild will not become a zombie.
1380 GPid grandchild_pid
;
1382 grandchild_pid
= fork ();
1384 if (grandchild_pid
< 0)
1386 /* report -1 as child PID */
1387 write_all (child_pid_report_pipe
[1], &grandchild_pid
,
1388 sizeof(grandchild_pid
));
1390 write_err_and_exit (child_err_report_pipe
[1],
1393 else if (grandchild_pid
== 0)
1395 close_and_invalidate (&child_pid_report_pipe
[1]);
1396 do_exec (child_err_report_pipe
[1],
1405 search_path_from_envp
,
1408 child_inherits_stdin
,
1415 write_all (child_pid_report_pipe
[1], &grandchild_pid
, sizeof(grandchild_pid
));
1416 close_and_invalidate (&child_pid_report_pipe
[1]);
1423 /* Just run the child.
1426 do_exec (child_err_report_pipe
[1],
1435 search_path_from_envp
,
1438 child_inherits_stdin
,
1451 /* Close the uncared-about ends of the pipes */
1452 close_and_invalidate (&child_err_report_pipe
[1]);
1453 close_and_invalidate (&child_pid_report_pipe
[1]);
1454 close_and_invalidate (&stdin_pipe
[0]);
1455 close_and_invalidate (&stdout_pipe
[1]);
1456 close_and_invalidate (&stderr_pipe
[1]);
1458 /* If we had an intermediate child, reap it */
1459 if (intermediate_child
)
1462 if (waitpid (pid
, &status
, 0) < 0)
1466 else if (errno
== ECHILD
)
1467 ; /* do nothing, child already reaped */
1469 g_warning ("waitpid() should not fail in "
1470 "'fork_exec_with_pipes'");
1475 if (!read_ints (child_err_report_pipe
[0],
1478 goto cleanup_and_fail
;
1482 /* Error from the child. */
1486 case CHILD_CHDIR_FAILED
:
1489 G_SPAWN_ERROR_CHDIR
,
1490 _("Failed to change to directory '%s' (%s)"),
1492 g_strerror (buf
[1]));
1496 case CHILD_EXEC_FAILED
:
1499 exec_err_to_g_error (buf
[1]),
1500 _("Failed to execute child process \"%s\" (%s)"),
1502 g_strerror (buf
[1]));
1506 case CHILD_DUP2_FAILED
:
1509 G_SPAWN_ERROR_FAILED
,
1510 _("Failed to redirect output or input of child process (%s)"),
1511 g_strerror (buf
[1]));
1515 case CHILD_FORK_FAILED
:
1519 _("Failed to fork child process (%s)"),
1520 g_strerror (buf
[1]));
1526 G_SPAWN_ERROR_FAILED
,
1527 _("Unknown error executing child process \"%s\""),
1532 goto cleanup_and_fail
;
1535 /* Get child pid from intermediate child pipe. */
1536 if (intermediate_child
)
1540 if (!read_ints (child_pid_report_pipe
[0],
1541 buf
, 1, &n_ints
, error
))
1542 goto cleanup_and_fail
;
1550 G_SPAWN_ERROR_FAILED
,
1551 _("Failed to read enough data from child pid pipe (%s)"),
1552 g_strerror (errsv
));
1553 goto cleanup_and_fail
;
1557 /* we have the child pid */
1562 /* Success against all odds! return the information */
1563 close_and_invalidate (&child_err_report_pipe
[0]);
1564 close_and_invalidate (&child_pid_report_pipe
[0]);
1570 *standard_input
= stdin_pipe
[1];
1571 if (standard_output
)
1572 *standard_output
= stdout_pipe
[0];
1574 *standard_error
= stderr_pipe
[0];
1581 /* There was an error from the Child, reap the child to avoid it being
1588 if (waitpid (pid
, NULL
, 0) < 0)
1592 else if (errno
== ECHILD
)
1593 ; /* do nothing, child already reaped */
1595 g_warning ("waitpid() should not fail in "
1596 "'fork_exec_with_pipes'");
1600 close_and_invalidate (&child_err_report_pipe
[0]);
1601 close_and_invalidate (&child_err_report_pipe
[1]);
1602 close_and_invalidate (&child_pid_report_pipe
[0]);
1603 close_and_invalidate (&child_pid_report_pipe
[1]);
1604 close_and_invalidate (&stdin_pipe
[0]);
1605 close_and_invalidate (&stdin_pipe
[1]);
1606 close_and_invalidate (&stdout_pipe
[0]);
1607 close_and_invalidate (&stdout_pipe
[1]);
1608 close_and_invalidate (&stderr_pipe
[0]);
1609 close_and_invalidate (&stderr_pipe
[1]);
1614 /* Based on execvp from GNU C Library */
1617 script_execute (const gchar
*file
,
1621 /* Count the arguments. */
1626 /* Construct an argument list for the shell. */
1630 new_argv
= g_new0 (gchar
*, argc
+ 2); /* /bin/sh and NULL */
1632 new_argv
[0] = (char *) "/bin/sh";
1633 new_argv
[1] = (char *) file
;
1636 new_argv
[argc
+ 1] = argv
[argc
];
1640 /* Execute the shell. */
1642 execve (new_argv
[0], new_argv
, envp
);
1644 execv (new_argv
[0], new_argv
);
1651 my_strchrnul (const gchar
*str
, gchar c
)
1653 gchar
*p
= (gchar
*) str
;
1654 while (*p
&& (*p
!= c
))
1661 g_execute (const gchar
*file
,
1664 gboolean search_path
,
1665 gboolean search_path_from_envp
)
1669 /* We check the simple case first. */
1674 if (!(search_path
|| search_path_from_envp
) || strchr (file
, '/') != NULL
)
1676 /* Don't search when it contains a slash. */
1678 execve (file
, argv
, envp
);
1682 if (errno
== ENOEXEC
)
1683 script_execute (file
, argv
, envp
);
1687 gboolean got_eacces
= 0;
1688 const gchar
*path
, *p
;
1689 gchar
*name
, *freeme
;
1694 if (search_path_from_envp
)
1695 path
= g_environ_getenv (envp
, "PATH");
1696 if (search_path
&& path
== NULL
)
1697 path
= g_getenv ("PATH");
1701 /* There is no 'PATH' in the environment. The default
1702 * search path in libc is the current directory followed by
1703 * the path 'confstr' returns for '_CS_PATH'.
1706 /* In GLib we put . last, for security, and don't use the
1707 * unportable confstr(); UNIX98 does not actually specify
1708 * what to search if PATH is unset. POSIX may, dunno.
1711 path
= "/bin:/usr/bin:.";
1714 len
= strlen (file
) + 1;
1715 pathlen
= strlen (path
);
1716 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
1718 /* Copy the file name at the top, including '\0' */
1719 memcpy (name
+ pathlen
+ 1, file
, len
);
1720 name
= name
+ pathlen
;
1721 /* And add the slash before the filename */
1730 p
= my_strchrnul (path
, ':');
1733 /* Two adjacent colons, or a colon at the beginning or the end
1734 * of 'PATH' means to search the current directory.
1738 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
1740 /* Try to execute this name. If it works, execv will not return. */
1742 execve (startp
, argv
, envp
);
1744 execv (startp
, argv
);
1746 if (errno
== ENOEXEC
)
1747 script_execute (startp
, argv
, envp
);
1752 /* Record the we got a 'Permission denied' error. If we end
1753 * up finding no executable we can use, we want to diagnose
1754 * that we did find one but were denied access.
1767 /* Those errors indicate the file is missing or not executable
1768 * by us, in which case we want to just try the next path
1775 /* Some strange filesystems like AFS return even
1776 * stranger error numbers. They cannot reasonably mean anything
1777 * else so ignore those, too.
1782 /* Some other error means we found an executable file, but
1783 * something went wrong executing it; return the error to our
1790 while (*p
++ != '\0');
1792 /* We tried every element and none of them worked. */
1794 /* At least one failure was due to permissions, so report that
1802 /* Return the error from the last attempt (probably ENOENT). */
1807 * g_spawn_close_pid:
1808 * @pid: The process reference to close
1810 * On some platforms, notably Windows, the #GPid type represents a resource
1811 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1812 * is provided for this purpose. It should be used on all platforms, even
1813 * though it doesn't do anything under UNIX.
1816 g_spawn_close_pid (GPid pid
)