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 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library 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 License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
24 #include <sys/types.h>
31 #include <stdlib.h> /* for fdwalk */
34 #ifdef HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
40 #endif /* HAVE_SYS_RESOURCE_H */
44 #include "glib/gstdio.h"
50 #include "gstrfuncs.h"
51 #include "gtestutils.h"
54 #include "glib-unix.h"
58 * @Short_description: process launching
59 * @Title: Spawning Processes
61 * GLib supports spawning of processes with an API that is more
62 * convenient than the bare UNIX fork() and exec().
64 * The g_spawn family of functions has synchronous (g_spawn_sync())
65 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
66 * as well as convenience variants that take a complete shell-like
67 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
69 * See #GSubprocess in GIO for a higher-level API that provides
70 * stream interfaces for communication with child processes.
72 * An example of using g_spawn_async_with_pipes():
73 * |[<!-- language="C" -->
74 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
75 * gint child_stdout, child_stderr;
77 * g_autoptr(GError) error = NULL;
79 * // Spawn child process.
80 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
81 * NULL, &child_pid, NULL, &child_stdout,
82 * &child_stderr, &error);
85 * g_error ("Spawning child failed: %s", error->message);
89 * // Add a child watch function which will be called when the child process
91 * g_child_watch_add (child_pid, child_watch_cb, NULL);
93 * // You could watch for output on @child_stdout and @child_stderr using
94 * // #GUnixInputStream or #GIOChannel here.
97 * child_watch_cb (GPid pid,
101 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
102 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
104 * // Free any resources associated with the child here, such as I/O channels
105 * // on its stdout and stderr FDs. If you have no code to put in the
106 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
107 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
108 * // otherwise the child process will stay around as a zombie until this
111 * g_spawn_close_pid (pid);
118 static gint
g_execute (const gchar
*file
,
121 gboolean search_path
,
122 gboolean search_path_from_envp
);
124 static gboolean
fork_exec_with_pipes (gboolean intermediate_child
,
125 const gchar
*working_directory
,
128 gboolean close_descriptors
,
129 gboolean search_path
,
130 gboolean search_path_from_envp
,
131 gboolean stdout_to_null
,
132 gboolean stderr_to_null
,
133 gboolean child_inherits_stdin
,
134 gboolean file_and_argv_zero
,
135 gboolean cloexec_pipes
,
136 GSpawnChildSetupFunc child_setup
,
139 gint
*standard_input
,
140 gint
*standard_output
,
141 gint
*standard_error
,
144 G_DEFINE_QUARK (g
-exec
-error
-quark
, g_spawn_error
)
145 G_DEFINE_QUARK (g
-spawn
-exit
-error
-quark
, g_spawn_exit_error
)
149 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
150 * @argv: (array zero-terminated=1): child's argument vector
151 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
152 * @flags: flags from #GSpawnFlags
153 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
154 * @user_data: (closure): user data for @child_setup
155 * @child_pid: (out) (optional): return location for child process reference, or %NULL
156 * @error: return location for error
158 * See g_spawn_async_with_pipes() for a full description; this function
159 * simply calls the g_spawn_async_with_pipes() without any pipes.
161 * You should call g_spawn_close_pid() on the returned child process
162 * reference when you don't need it any more.
164 * If you are writing a GTK+ application, and the program you are spawning is a
165 * graphical application too, then to ensure that the spawned program opens its
166 * windows on the right screen, you may want to use #GdkAppLaunchContext,
167 * #GAppLaunchcontext, or set the %DISPLAY environment variable.
169 * Note that the returned @child_pid on Windows is a handle to the child
170 * process and not its identifier. Process handles and process identifiers
171 * are different concepts on Windows.
173 * Returns: %TRUE on success, %FALSE if error is set
176 g_spawn_async (const gchar
*working_directory
,
180 GSpawnChildSetupFunc child_setup
,
185 g_return_val_if_fail (argv
!= NULL
, FALSE
);
187 return g_spawn_async_with_pipes (working_directory
,
197 /* Avoids a danger in threaded situations (calling close()
198 * on a file descriptor twice, and another thread has
199 * re-opened it since the first close)
202 close_and_invalidate (gint
*fd
)
208 (void) g_close (*fd
, NULL
);
213 /* Some versions of OS X define READ_OK in public headers */
218 READ_FAILED
= 0, /* FALSE */
224 read_data (GString
*str
,
232 bytes
= read (fd
, buf
, 4096);
238 g_string_append_len (str
, buf
, bytes
);
241 else if (errno
== EINTR
)
250 _("Failed to read data from child process (%s)"),
259 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
260 * @argv: (array zero-terminated=1): child's argument vector
261 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
262 * @flags: flags from #GSpawnFlags
263 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
264 * @user_data: (closure): user data for @child_setup
265 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
266 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
267 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
268 * @error: return location for error, or %NULL
270 * Executes a child synchronously (waits for the child to exit before returning).
271 * All output from the child is stored in @standard_output and @standard_error,
272 * if those parameters are non-%NULL. Note that you must set the
273 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
274 * passing %NULL for @standard_output and @standard_error.
276 * If @exit_status is non-%NULL, the platform-specific exit status of
277 * the child is stored there; see the documentation of
278 * g_spawn_check_exit_status() for how to use and interpret this.
279 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
280 * @flags, and on POSIX platforms, the same restrictions as for
281 * g_child_watch_source_new() apply.
283 * If an error occurs, no data is returned in @standard_output,
284 * @standard_error, or @exit_status.
286 * This function calls g_spawn_async_with_pipes() internally; see that
287 * function for full details on the other parameters and details on
288 * how these functions work on Windows.
290 * Returns: %TRUE on success, %FALSE if an error was set
293 g_spawn_sync (const gchar
*working_directory
,
297 GSpawnChildSetupFunc child_setup
,
299 gchar
**standard_output
,
300 gchar
**standard_error
,
309 GString
*outstr
= NULL
;
310 GString
*errstr
= NULL
;
314 g_return_val_if_fail (argv
!= NULL
, FALSE
);
315 g_return_val_if_fail (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
), FALSE
);
316 g_return_val_if_fail (standard_output
== NULL
||
317 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
318 g_return_val_if_fail (standard_error
== NULL
||
319 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
321 /* Just to ensure segfaults if callers try to use
322 * these when an error is reported.
325 *standard_output
= NULL
;
328 *standard_error
= NULL
;
330 if (!fork_exec_with_pipes (FALSE
,
334 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
335 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
336 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
337 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
338 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
339 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
340 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
341 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
346 standard_output
? &outpipe
: NULL
,
347 standard_error
? &errpipe
: NULL
,
351 /* Read data from child. */
357 outstr
= g_string_new (NULL
);
362 errstr
= g_string_new (NULL
);
365 /* Read data until we get EOF on both pipes. */
374 FD_SET (outpipe
, &fds
);
376 FD_SET (errpipe
, &fds
);
378 ret
= select (MAX (outpipe
, errpipe
) + 1,
381 NULL
/* no timeout */);
395 _("Unexpected error in select() reading data from a child process (%s)"),
401 if (outpipe
>= 0 && FD_ISSET (outpipe
, &fds
))
403 switch (read_data (outstr
, outpipe
, error
))
409 close_and_invalidate (&outpipe
);
420 if (errpipe
>= 0 && FD_ISSET (errpipe
, &fds
))
422 switch (read_data (errstr
, errpipe
, error
))
428 close_and_invalidate (&errpipe
);
440 /* These should only be open still if we had an error. */
443 close_and_invalidate (&outpipe
);
445 close_and_invalidate (&errpipe
);
447 /* Wait for child to exit, even if we have
452 ret
= waitpid (pid
, &status
, 0);
458 else if (errno
== ECHILD
)
462 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
466 /* We don't need the exit status. */
471 if (!failed
) /* avoid error pileups */
480 _("Unexpected error in waitpid() (%s)"),
489 g_string_free (outstr
, TRUE
);
491 g_string_free (errstr
, TRUE
);
498 *exit_status
= status
;
501 *standard_output
= g_string_free (outstr
, FALSE
);
504 *standard_error
= g_string_free (errstr
, FALSE
);
511 * g_spawn_async_with_pipes:
512 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
513 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
514 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
515 * @flags: flags from #GSpawnFlags
516 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
517 * @user_data: (closure): user data for @child_setup
518 * @child_pid: (out) (optional): return location for child process ID, or %NULL
519 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
520 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
521 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
522 * @error: return location for error
524 * Executes a child program asynchronously (your program will not
525 * block waiting for the child to exit). The child program is
526 * specified by the only argument that must be provided, @argv.
527 * @argv should be a %NULL-terminated array of strings, to be passed
528 * as the argument vector for the child. The first string in @argv
529 * is of course the name of the program to execute. By default, the
530 * name of the program must be a full path. If @flags contains the
531 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
532 * used to search for the executable. If @flags contains the
533 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
534 * @envp is used to search for the executable. If both the
535 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
536 * are set, the `PATH` variable from @envp takes precedence over
537 * the environment variable.
539 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
540 * used, then the program will be run from the current directory (or
541 * @working_directory, if specified); this might be unexpected or even
542 * dangerous in some cases when the current directory is world-writable.
544 * On Windows, note that all the string or string vector arguments to
545 * this function and the other g_spawn*() functions are in UTF-8, the
546 * GLib file name encoding. Unicode characters that are not part of
547 * the system codepage passed in these arguments will be correctly
548 * available in the spawned program only if it uses wide character API
549 * to retrieve its command line. For C programs built with Microsoft's
550 * tools it is enough to make the program have a wmain() instead of
551 * main(). wmain() has a wide character argument vector as parameter.
553 * At least currently, mingw doesn't support wmain(), so if you use
554 * mingw to develop the spawned program, it should call
555 * g_win32_get_command_line() to get arguments in UTF-8.
557 * On Windows the low-level child process creation API CreateProcess()
558 * doesn't use argument vectors, but a command line. The C runtime
559 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
560 * eventually calls) paste the argument vector elements together into
561 * a command line, and the C runtime startup code does a corresponding
562 * reconstruction of an argument vector from the command line, to be
563 * passed to main(). Complications arise when you have argument vector
564 * elements that contain spaces of double quotes. The spawn*() functions
565 * don't do any quoting or escaping, but on the other hand the startup
566 * code does do unquoting and unescaping in order to enable receiving
567 * arguments with embedded spaces or double quotes. To work around this
568 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
569 * argument vector elements that need it before calling the C runtime
572 * The returned @child_pid on Windows is a handle to the child
573 * process, not its identifier. Process handles and process
574 * identifiers are different concepts on Windows.
576 * @envp is a %NULL-terminated array of strings, where each string
577 * has the form `KEY=VALUE`. This will become the child's environment.
578 * If @envp is %NULL, the child inherits its parent's environment.
580 * @flags should be the bitwise OR of any flags you want to affect the
581 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
582 * child will not automatically be reaped; you must use a child watch
583 * (g_child_watch_add()) to be notified about the death of the child process,
584 * otherwise it will stay around as a zombie process until this process exits.
585 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
586 * free resources which may be associated with the child process. (On Unix,
587 * using a child watch is equivalent to calling waitpid() or handling
588 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
589 * is equivalent to calling CloseHandle() on the process handle returned
590 * in @child_pid). See g_child_watch_add().
592 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
593 * descriptors will be inherited by the child; otherwise all descriptors
594 * except stdin/stdout/stderr will be closed before calling exec() in
595 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
596 * absolute path, it will be looked for in the `PATH` environment
597 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
598 * absolute path, it will be looked for in the `PATH` variable from
599 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
600 * are used, the value from @envp takes precedence over the environment.
601 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
602 * will be discarded, instead of going to the same location as the parent's
603 * standard output. If you use this flag, @standard_output must be %NULL.
604 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
605 * will be discarded, instead of going to the same location as the parent's
606 * standard error. If you use this flag, @standard_error must be %NULL.
607 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
608 * standard input (by default, the child's standard input is attached to
609 * /dev/null). If you use this flag, @standard_input must be %NULL.
610 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
611 * the file to execute, while the remaining elements are the actual
612 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
613 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
615 * @child_setup and @user_data are a function and user data. On POSIX
616 * platforms, the function is called in the child after GLib has
617 * performed all the setup it plans to perform (including creating
618 * pipes, closing file descriptors, etc.) but before calling exec().
619 * That is, @child_setup is called just before calling exec() in the
620 * child. Obviously actions taken in this function will only affect
621 * the child, not the parent.
623 * On Windows, there is no separate fork() and exec() functionality.
624 * Child processes are created and run with a single API call,
625 * CreateProcess(). There is no sensible thing @child_setup
626 * could be used for on Windows so it is ignored and not called.
628 * If non-%NULL, @child_pid will on Unix be filled with the child's
629 * process ID. You can use the process ID to send signals to the child,
630 * or to use g_child_watch_add() (or waitpid()) if you specified the
631 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
632 * filled with a handle to the child process only if you specified the
633 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
634 * process using the Win32 API, for example wait for its termination
635 * with the WaitFor*() functions, or examine its exit code with
636 * GetExitCodeProcess(). You should close the handle with CloseHandle()
637 * or g_spawn_close_pid() when you no longer need it.
639 * If non-%NULL, the @standard_input, @standard_output, @standard_error
640 * locations will be filled with file descriptors for writing to the child's
641 * standard input or reading from its standard output or standard error.
642 * The caller of g_spawn_async_with_pipes() must close these file descriptors
643 * when they are no longer in use. If these parameters are %NULL, the
644 * corresponding pipe won't be created.
646 * If @standard_input is NULL, the child's standard input is attached to
647 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
649 * If @standard_error is NULL, the child's standard error goes to the same
650 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
653 * If @standard_output is NULL, the child's standard output goes to the same
654 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
657 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
658 * If an error is set, the function returns %FALSE. Errors are reported
659 * even if they occur in the child (for example if the executable in
660 * @argv[0] is not found). Typically the `message` field of returned
661 * errors should be displayed to users. Possible errors are those from
662 * the #G_SPAWN_ERROR domain.
664 * If an error occurs, @child_pid, @standard_input, @standard_output,
665 * and @standard_error will not be filled with valid values.
667 * If @child_pid is not %NULL and an error does not occur then the returned
668 * process reference must be closed using g_spawn_close_pid().
670 * If you are writing a GTK+ application, and the program you are spawning is a
671 * graphical application too, then to ensure that the spawned program opens its
672 * windows on the right screen, you may want to use #GdkAppLaunchContext,
673 * #GAppLaunchcontext, or set the %DISPLAY environment variable.
675 * Returns: %TRUE on success, %FALSE if an error was set
678 g_spawn_async_with_pipes (const gchar
*working_directory
,
682 GSpawnChildSetupFunc child_setup
,
685 gint
*standard_input
,
686 gint
*standard_output
,
687 gint
*standard_error
,
690 g_return_val_if_fail (argv
!= NULL
, FALSE
);
691 g_return_val_if_fail (standard_output
== NULL
||
692 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
693 g_return_val_if_fail (standard_error
== NULL
||
694 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
695 /* can't inherit stdin if we have an input pipe. */
696 g_return_val_if_fail (standard_input
== NULL
||
697 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
699 return fork_exec_with_pipes (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
703 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
704 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
705 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
706 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
707 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
708 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
709 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
710 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
721 * g_spawn_command_line_sync:
722 * @command_line: a command line
723 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
724 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
725 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
726 * @error: return location for errors
728 * A simple version of g_spawn_sync() with little-used parameters
729 * removed, taking a command line instead of an argument vector. See
730 * g_spawn_sync() for full details. @command_line will be parsed by
731 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
732 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
733 * implications, so consider using g_spawn_sync() directly if
734 * appropriate. Possible errors are those from g_spawn_sync() and those
735 * from g_shell_parse_argv().
737 * If @exit_status is non-%NULL, the platform-specific exit status of
738 * the child is stored there; see the documentation of
739 * g_spawn_check_exit_status() for how to use and interpret this.
741 * On Windows, please note the implications of g_shell_parse_argv()
742 * parsing @command_line. Parsing is done according to Unix shell rules, not
743 * Windows command interpreter rules.
744 * Space is a separator, and backslashes are
745 * special. Thus you cannot simply pass a @command_line containing
746 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
747 * the backslashes will be eaten, and the space will act as a
748 * separator. You need to enclose such paths with single quotes, like
749 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
751 * Returns: %TRUE on success, %FALSE if an error was set
754 g_spawn_command_line_sync (const gchar
*command_line
,
755 gchar
**standard_output
,
756 gchar
**standard_error
,
763 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
765 if (!g_shell_parse_argv (command_line
,
770 retval
= g_spawn_sync (NULL
,
786 * g_spawn_command_line_async:
787 * @command_line: a command line
788 * @error: return location for errors
790 * A simple version of g_spawn_async() that parses a command line with
791 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
792 * command line in the background. Unlike g_spawn_async(), the
793 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
794 * that %G_SPAWN_SEARCH_PATH can have security implications, so
795 * consider using g_spawn_async() directly if appropriate. Possible
796 * errors are those from g_shell_parse_argv() and g_spawn_async().
798 * The same concerns on Windows apply as for g_spawn_command_line_sync().
800 * Returns: %TRUE on success, %FALSE if error is set
803 g_spawn_command_line_async (const gchar
*command_line
,
809 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
811 if (!g_shell_parse_argv (command_line
,
816 retval
= g_spawn_async (NULL
,
830 * g_spawn_check_exit_status:
831 * @exit_status: An exit code as returned from g_spawn_sync()
834 * Set @error if @exit_status indicates the child exited abnormally
835 * (e.g. with a nonzero exit code, or via a fatal signal).
837 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
838 * exit status for subprocesses encoded in a platform-specific way.
839 * On Unix, this is guaranteed to be in the same format waitpid() returns,
840 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
842 * Prior to the introduction of this function in GLib 2.34, interpreting
843 * @exit_status required use of platform-specific APIs, which is problematic
844 * for software using GLib as a cross-platform layer.
846 * Additionally, many programs simply want to determine whether or not
847 * the child exited successfully, and either propagate a #GError or
848 * print a message to standard error. In that common case, this function
849 * can be used. Note that the error message in @error will contain
850 * human-readable information about the exit status.
852 * The @domain and @code of @error have special semantics in the case
853 * where the process has an "exit code", as opposed to being killed by
854 * a signal. On Unix, this happens if WIFEXITED() would be true of
855 * @exit_status. On Windows, it is always the case.
857 * The special semantics are that the actual exit code will be the
858 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
859 * This allows you to differentiate between different exit codes.
861 * If the process was terminated by some means other than an exit
862 * status, the domain will be %G_SPAWN_ERROR, and the code will be
863 * %G_SPAWN_ERROR_FAILED.
865 * This function just offers convenience; you can of course also check
866 * the available platform via a macro such as %G_OS_UNIX, and use
867 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
868 * to scan or parse the error message string; it may be translated and/or
869 * change in future versions of GLib.
871 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
872 * @error will be set)
877 g_spawn_check_exit_status (gint exit_status
,
880 gboolean ret
= FALSE
;
882 if (WIFEXITED (exit_status
))
884 if (WEXITSTATUS (exit_status
) != 0)
886 g_set_error (error
, G_SPAWN_EXIT_ERROR
, WEXITSTATUS (exit_status
),
887 _("Child process exited with code %ld"),
888 (long) WEXITSTATUS (exit_status
));
892 else if (WIFSIGNALED (exit_status
))
894 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
895 _("Child process killed by signal %ld"),
896 (long) WTERMSIG (exit_status
));
899 else if (WIFSTOPPED (exit_status
))
901 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
902 _("Child process stopped by signal %ld"),
903 (long) WSTOPSIG (exit_status
));
908 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
909 _("Child process exited abnormally"));
919 exec_err_to_g_error (gint en
)
925 return G_SPAWN_ERROR_ACCES
;
931 return G_SPAWN_ERROR_PERM
;
937 return G_SPAWN_ERROR_TOO_BIG
;
943 return G_SPAWN_ERROR_NOEXEC
;
949 return G_SPAWN_ERROR_NAMETOOLONG
;
955 return G_SPAWN_ERROR_NOENT
;
961 return G_SPAWN_ERROR_NOMEM
;
967 return G_SPAWN_ERROR_NOTDIR
;
973 return G_SPAWN_ERROR_LOOP
;
979 return G_SPAWN_ERROR_TXTBUSY
;
985 return G_SPAWN_ERROR_IO
;
991 return G_SPAWN_ERROR_NFILE
;
997 return G_SPAWN_ERROR_MFILE
;
1003 return G_SPAWN_ERROR_INVAL
;
1009 return G_SPAWN_ERROR_ISDIR
;
1015 return G_SPAWN_ERROR_LIBBAD
;
1020 return G_SPAWN_ERROR_FAILED
;
1026 write_all (gint fd
, gconstpointer vbuf
, gsize to_write
)
1028 gchar
*buf
= (gchar
*) vbuf
;
1030 while (to_write
> 0)
1032 gssize count
= write (fd
, buf
, to_write
);
1050 write_err_and_exit (gint fd
, gint msg
)
1054 write_all (fd
, &msg
, sizeof(msg
));
1055 write_all (fd
, &en
, sizeof(en
));
1061 set_cloexec (void *data
, gint fd
)
1063 if (fd
>= GPOINTER_TO_INT (data
))
1064 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
1071 fdwalk (int (*cb
)(void *data
, int fd
), void *data
)
1077 #ifdef HAVE_SYS_RESOURCE_H
1084 if ((d
= opendir("/proc/self/fd"))) {
1087 while ((de
= readdir(d
))) {
1091 if (de
->d_name
[0] == '.')
1095 l
= strtol(de
->d_name
, &e
, 10);
1096 if (errno
!= 0 || !e
|| *e
)
1101 if ((glong
) fd
!= l
)
1107 if ((res
= cb (data
, fd
)) != 0)
1115 /* If /proc is not mounted or not accessible we fall back to the old
1120 #ifdef HAVE_SYS_RESOURCE_H
1122 if (getrlimit(RLIMIT_NOFILE
, &rl
) == 0 && rl
.rlim_max
!= RLIM_INFINITY
)
1123 open_max
= rl
.rlim_max
;
1126 open_max
= sysconf (_SC_OPEN_MAX
);
1128 for (fd
= 0; fd
< open_max
; fd
++)
1129 if ((res
= cb (data
, fd
)) != 0)
1137 sane_dup2 (gint fd1
, gint fd2
)
1142 ret
= dup2 (fd1
, fd2
);
1143 if (ret
< 0 && errno
== EINTR
)
1150 sane_open (const char *path
, gint mode
)
1155 ret
= open (path
, mode
);
1156 if (ret
< 0 && errno
== EINTR
)
1171 do_exec (gint child_err_report_fd
,
1175 const gchar
*working_directory
,
1178 gboolean close_descriptors
,
1179 gboolean search_path
,
1180 gboolean search_path_from_envp
,
1181 gboolean stdout_to_null
,
1182 gboolean stderr_to_null
,
1183 gboolean child_inherits_stdin
,
1184 gboolean file_and_argv_zero
,
1185 GSpawnChildSetupFunc child_setup
,
1188 if (working_directory
&& chdir (working_directory
) < 0)
1189 write_err_and_exit (child_err_report_fd
,
1190 CHILD_CHDIR_FAILED
);
1192 /* Close all file descriptors but stdin stdout and stderr as
1193 * soon as we exec. Note that this includes
1194 * child_err_report_fd, which keeps the parent from blocking
1195 * forever on the other end of that pipe.
1197 if (close_descriptors
)
1199 fdwalk (set_cloexec
, GINT_TO_POINTER(3));
1203 /* We need to do child_err_report_fd anyway */
1204 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd
);
1207 /* Redirect pipes as required */
1211 /* dup2 can't actually fail here I don't think */
1213 if (sane_dup2 (stdin_fd
, 0) < 0)
1214 write_err_and_exit (child_err_report_fd
,
1217 /* ignore this if it doesn't work */
1218 close_and_invalidate (&stdin_fd
);
1220 else if (!child_inherits_stdin
)
1222 /* Keep process from blocking on a read of stdin */
1223 gint read_null
= open ("/dev/null", O_RDONLY
);
1224 g_assert (read_null
!= -1);
1225 sane_dup2 (read_null
, 0);
1226 close_and_invalidate (&read_null
);
1231 /* dup2 can't actually fail here I don't think */
1233 if (sane_dup2 (stdout_fd
, 1) < 0)
1234 write_err_and_exit (child_err_report_fd
,
1237 /* ignore this if it doesn't work */
1238 close_and_invalidate (&stdout_fd
);
1240 else if (stdout_to_null
)
1242 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1243 g_assert (write_null
!= -1);
1244 sane_dup2 (write_null
, 1);
1245 close_and_invalidate (&write_null
);
1250 /* dup2 can't actually fail here I don't think */
1252 if (sane_dup2 (stderr_fd
, 2) < 0)
1253 write_err_and_exit (child_err_report_fd
,
1256 /* ignore this if it doesn't work */
1257 close_and_invalidate (&stderr_fd
);
1259 else if (stderr_to_null
)
1261 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1262 sane_dup2 (write_null
, 2);
1263 close_and_invalidate (&write_null
);
1266 /* Call user function just before we exec */
1269 (* child_setup
) (user_data
);
1273 file_and_argv_zero
? argv
+ 1 : argv
,
1274 envp
, search_path
, search_path_from_envp
);
1277 write_err_and_exit (child_err_report_fd
,
1294 if (bytes
>= sizeof(gint
)*2)
1295 break; /* give up, who knows what happened, should not be
1301 ((gchar
*)buf
) + bytes
,
1302 sizeof(gint
) * n_ints_in_buf
- bytes
);
1303 if (chunk
< 0 && errno
== EINTR
)
1310 /* Some weird shit happened, bail out */
1313 G_SPAWN_ERROR_FAILED
,
1314 _("Failed to read from child pipe (%s)"),
1315 g_strerror (errsv
));
1319 else if (chunk
== 0)
1321 else /* chunk > 0 */
1325 *n_ints_read
= (gint
)(bytes
/ sizeof(gint
));
1331 fork_exec_with_pipes (gboolean intermediate_child
,
1332 const gchar
*working_directory
,
1335 gboolean close_descriptors
,
1336 gboolean search_path
,
1337 gboolean search_path_from_envp
,
1338 gboolean stdout_to_null
,
1339 gboolean stderr_to_null
,
1340 gboolean child_inherits_stdin
,
1341 gboolean file_and_argv_zero
,
1342 gboolean cloexec_pipes
,
1343 GSpawnChildSetupFunc child_setup
,
1346 gint
*standard_input
,
1347 gint
*standard_output
,
1348 gint
*standard_error
,
1352 gint stdin_pipe
[2] = { -1, -1 };
1353 gint stdout_pipe
[2] = { -1, -1 };
1354 gint stderr_pipe
[2] = { -1, -1 };
1355 gint child_err_report_pipe
[2] = { -1, -1 };
1356 gint child_pid_report_pipe
[2] = { -1, -1 };
1357 guint pipe_flags
= cloexec_pipes
? FD_CLOEXEC
: 0;
1360 if (!g_unix_open_pipe (child_err_report_pipe
, pipe_flags
, error
))
1363 if (intermediate_child
&& !g_unix_open_pipe (child_pid_report_pipe
, pipe_flags
, error
))
1364 goto cleanup_and_fail
;
1366 if (standard_input
&& !g_unix_open_pipe (stdin_pipe
, pipe_flags
, error
))
1367 goto cleanup_and_fail
;
1369 if (standard_output
&& !g_unix_open_pipe (stdout_pipe
, pipe_flags
, error
))
1370 goto cleanup_and_fail
;
1372 if (standard_error
&& !g_unix_open_pipe (stderr_pipe
, FD_CLOEXEC
, error
))
1373 goto cleanup_and_fail
;
1384 _("Failed to fork (%s)"),
1385 g_strerror (errsv
));
1387 goto cleanup_and_fail
;
1391 /* Immediate child. This may or may not be the child that
1392 * actually execs the new process.
1395 /* Reset some signal handlers that we may use */
1396 signal (SIGCHLD
, SIG_DFL
);
1397 signal (SIGINT
, SIG_DFL
);
1398 signal (SIGTERM
, SIG_DFL
);
1399 signal (SIGHUP
, SIG_DFL
);
1401 /* Be sure we crash if the parent exits
1402 * and we write to the err_report_pipe
1404 signal (SIGPIPE
, SIG_DFL
);
1406 /* Close the parent's end of the pipes;
1407 * not needed in the close_descriptors case,
1410 close_and_invalidate (&child_err_report_pipe
[0]);
1411 close_and_invalidate (&child_pid_report_pipe
[0]);
1412 close_and_invalidate (&stdin_pipe
[1]);
1413 close_and_invalidate (&stdout_pipe
[0]);
1414 close_and_invalidate (&stderr_pipe
[0]);
1416 if (intermediate_child
)
1418 /* We need to fork an intermediate child that launches the
1419 * final child. The purpose of the intermediate child
1420 * is to exit, so we can waitpid() it immediately.
1421 * Then the grandchild will not become a zombie.
1423 GPid grandchild_pid
;
1425 grandchild_pid
= fork ();
1427 if (grandchild_pid
< 0)
1429 /* report -1 as child PID */
1430 write_all (child_pid_report_pipe
[1], &grandchild_pid
,
1431 sizeof(grandchild_pid
));
1433 write_err_and_exit (child_err_report_pipe
[1],
1436 else if (grandchild_pid
== 0)
1438 close_and_invalidate (&child_pid_report_pipe
[1]);
1439 do_exec (child_err_report_pipe
[1],
1448 search_path_from_envp
,
1451 child_inherits_stdin
,
1458 write_all (child_pid_report_pipe
[1], &grandchild_pid
, sizeof(grandchild_pid
));
1459 close_and_invalidate (&child_pid_report_pipe
[1]);
1466 /* Just run the child.
1469 do_exec (child_err_report_pipe
[1],
1478 search_path_from_envp
,
1481 child_inherits_stdin
,
1494 /* Close the uncared-about ends of the pipes */
1495 close_and_invalidate (&child_err_report_pipe
[1]);
1496 close_and_invalidate (&child_pid_report_pipe
[1]);
1497 close_and_invalidate (&stdin_pipe
[0]);
1498 close_and_invalidate (&stdout_pipe
[1]);
1499 close_and_invalidate (&stderr_pipe
[1]);
1501 /* If we had an intermediate child, reap it */
1502 if (intermediate_child
)
1505 if (waitpid (pid
, &status
, 0) < 0)
1509 else if (errno
== ECHILD
)
1510 ; /* do nothing, child already reaped */
1512 g_warning ("waitpid() should not fail in "
1513 "'fork_exec_with_pipes'");
1518 if (!read_ints (child_err_report_pipe
[0],
1521 goto cleanup_and_fail
;
1525 /* Error from the child. */
1529 case CHILD_CHDIR_FAILED
:
1532 G_SPAWN_ERROR_CHDIR
,
1533 _("Failed to change to directory “%s” (%s)"),
1535 g_strerror (buf
[1]));
1539 case CHILD_EXEC_FAILED
:
1542 exec_err_to_g_error (buf
[1]),
1543 _("Failed to execute child process “%s” (%s)"),
1545 g_strerror (buf
[1]));
1549 case CHILD_DUP2_FAILED
:
1552 G_SPAWN_ERROR_FAILED
,
1553 _("Failed to redirect output or input of child process (%s)"),
1554 g_strerror (buf
[1]));
1558 case CHILD_FORK_FAILED
:
1562 _("Failed to fork child process (%s)"),
1563 g_strerror (buf
[1]));
1569 G_SPAWN_ERROR_FAILED
,
1570 _("Unknown error executing child process “%s”"),
1575 goto cleanup_and_fail
;
1578 /* Get child pid from intermediate child pipe. */
1579 if (intermediate_child
)
1583 if (!read_ints (child_pid_report_pipe
[0],
1584 buf
, 1, &n_ints
, error
))
1585 goto cleanup_and_fail
;
1593 G_SPAWN_ERROR_FAILED
,
1594 _("Failed to read enough data from child pid pipe (%s)"),
1595 g_strerror (errsv
));
1596 goto cleanup_and_fail
;
1600 /* we have the child pid */
1605 /* Success against all odds! return the information */
1606 close_and_invalidate (&child_err_report_pipe
[0]);
1607 close_and_invalidate (&child_pid_report_pipe
[0]);
1613 *standard_input
= stdin_pipe
[1];
1614 if (standard_output
)
1615 *standard_output
= stdout_pipe
[0];
1617 *standard_error
= stderr_pipe
[0];
1624 /* There was an error from the Child, reap the child to avoid it being
1631 if (waitpid (pid
, NULL
, 0) < 0)
1635 else if (errno
== ECHILD
)
1636 ; /* do nothing, child already reaped */
1638 g_warning ("waitpid() should not fail in "
1639 "'fork_exec_with_pipes'");
1643 close_and_invalidate (&child_err_report_pipe
[0]);
1644 close_and_invalidate (&child_err_report_pipe
[1]);
1645 close_and_invalidate (&child_pid_report_pipe
[0]);
1646 close_and_invalidate (&child_pid_report_pipe
[1]);
1647 close_and_invalidate (&stdin_pipe
[0]);
1648 close_and_invalidate (&stdin_pipe
[1]);
1649 close_and_invalidate (&stdout_pipe
[0]);
1650 close_and_invalidate (&stdout_pipe
[1]);
1651 close_and_invalidate (&stderr_pipe
[0]);
1652 close_and_invalidate (&stderr_pipe
[1]);
1657 /* Based on execvp from GNU C Library */
1660 script_execute (const gchar
*file
,
1664 /* Count the arguments. */
1669 /* Construct an argument list for the shell. */
1673 new_argv
= g_new0 (gchar
*, argc
+ 2); /* /bin/sh and NULL */
1675 new_argv
[0] = (char *) "/bin/sh";
1676 new_argv
[1] = (char *) file
;
1679 new_argv
[argc
+ 1] = argv
[argc
];
1683 /* Execute the shell. */
1685 execve (new_argv
[0], new_argv
, envp
);
1687 execv (new_argv
[0], new_argv
);
1694 my_strchrnul (const gchar
*str
, gchar c
)
1696 gchar
*p
= (gchar
*) str
;
1697 while (*p
&& (*p
!= c
))
1704 g_execute (const gchar
*file
,
1707 gboolean search_path
,
1708 gboolean search_path_from_envp
)
1712 /* We check the simple case first. */
1717 if (!(search_path
|| search_path_from_envp
) || strchr (file
, '/') != NULL
)
1719 /* Don't search when it contains a slash. */
1721 execve (file
, argv
, envp
);
1725 if (errno
== ENOEXEC
)
1726 script_execute (file
, argv
, envp
);
1730 gboolean got_eacces
= 0;
1731 const gchar
*path
, *p
;
1732 gchar
*name
, *freeme
;
1737 if (search_path_from_envp
)
1738 path
= g_environ_getenv (envp
, "PATH");
1739 if (search_path
&& path
== NULL
)
1740 path
= g_getenv ("PATH");
1744 /* There is no 'PATH' in the environment. The default
1745 * search path in libc is the current directory followed by
1746 * the path 'confstr' returns for '_CS_PATH'.
1749 /* In GLib we put . last, for security, and don't use the
1750 * unportable confstr(); UNIX98 does not actually specify
1751 * what to search if PATH is unset. POSIX may, dunno.
1754 path
= "/bin:/usr/bin:.";
1757 len
= strlen (file
) + 1;
1758 pathlen
= strlen (path
);
1759 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
1761 /* Copy the file name at the top, including '\0' */
1762 memcpy (name
+ pathlen
+ 1, file
, len
);
1763 name
= name
+ pathlen
;
1764 /* And add the slash before the filename */
1773 p
= my_strchrnul (path
, ':');
1776 /* Two adjacent colons, or a colon at the beginning or the end
1777 * of 'PATH' means to search the current directory.
1781 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
1783 /* Try to execute this name. If it works, execv will not return. */
1785 execve (startp
, argv
, envp
);
1787 execv (startp
, argv
);
1789 if (errno
== ENOEXEC
)
1790 script_execute (startp
, argv
, envp
);
1795 /* Record the we got a 'Permission denied' error. If we end
1796 * up finding no executable we can use, we want to diagnose
1797 * that we did find one but were denied access.
1810 /* Those errors indicate the file is missing or not executable
1811 * by us, in which case we want to just try the next path
1818 /* Some strange filesystems like AFS return even
1819 * stranger error numbers. They cannot reasonably mean anything
1820 * else so ignore those, too.
1825 /* Some other error means we found an executable file, but
1826 * something went wrong executing it; return the error to our
1833 while (*p
++ != '\0');
1835 /* We tried every element and none of them worked. */
1837 /* At least one failure was due to permissions, so report that
1845 /* Return the error from the last attempt (probably ENOENT). */
1850 * g_spawn_close_pid:
1851 * @pid: The process reference to close
1853 * On some platforms, notably Windows, the #GPid type represents a resource
1854 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1855 * is provided for this purpose. It should be used on all platforms, even
1856 * though it doesn't do anything under UNIX.
1859 g_spawn_close_pid (GPid pid
)