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 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this library; if not, see <http://www.gnu.org/licenses/>.
26 #include <sys/types.h>
33 #include <stdlib.h> /* for fdwalk */
39 #endif /* HAVE_SPAWN_H */
41 #ifdef HAVE_CRT_EXTERNS_H
42 #include <crt_externs.h> /* for _NSGetEnviron */
45 #ifdef HAVE_SYS_SELECT_H
46 #include <sys/select.h>
47 #endif /* HAVE_SYS_SELECT_H */
49 #ifdef HAVE_SYS_RESOURCE_H
50 #include <sys/resource.h>
51 #endif /* HAVE_SYS_RESOURCE_H */
53 #if defined(__linux__) || defined(__DragonFly__)
54 #include <sys/syscall.h> /* for syscall and SYS_getdents64 */
58 #include "gspawn-private.h"
60 #include "gtrace-private.h"
61 #include "glib/gstdio.h"
67 #include "gstrfuncs.h"
68 #include "gtestutils.h"
71 #include "glib-unix.h"
75 #include <sys/proc_info.h>
78 #define INHERITS_OR_NULL_STDIN (G_SPAWN_STDIN_FROM_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDIN)
79 #define INHERITS_OR_NULL_STDOUT (G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDOUT)
80 #define INHERITS_OR_NULL_STDERR (G_SPAWN_STDERR_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDERR)
82 #define IS_STD_FILENO(_fd) ((_fd >= STDIN_FILENO) && (_fd <= STDERR_FILENO))
83 #define IS_VALID_FILENO(_fd) (_fd >= 0)
85 /* posix_spawn() is assumed the fastest way to spawn, but glibc's
86 * implementation was buggy before glibc 2.24, so avoid it on old versions.
88 #ifdef HAVE_POSIX_SPAWN
91 #if __GLIBC_PREREQ(2,24)
92 #define POSIX_SPAWN_AVAILABLE
95 #else /* !__GLIBC__ */
96 /* Assume that all non-glibc posix_spawn implementations are fine. */
97 #define POSIX_SPAWN_AVAILABLE
98 #endif /* __GLIBC__ */
99 #endif /* HAVE_POSIX_SPAWN */
101 #ifdef HAVE__NSGETENVIRON
102 #define environ (*_NSGetEnviron())
104 extern char **environ;
110 #define HAVE_O_CLOEXEC 1
115 * @Short_description: process launching
116 * @Title: Spawning Processes
118 * GLib supports spawning of processes with an API that is more
119 * convenient than the bare UNIX fork() and exec().
121 * The g_spawn family of functions has synchronous (g_spawn_sync())
122 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
123 * as well as convenience variants that take a complete shell-like
124 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
126 * See #GSubprocess in GIO for a higher-level API that provides
127 * stream interfaces for communication with child processes.
129 * An example of using g_spawn_async_with_pipes():
130 * |[<!-- language="C" -->
131 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
132 * gint child_stdout, child_stderr;
134 * g_autoptr(GError) error = NULL;
136 * // Spawn child process.
137 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
138 * NULL, &child_pid, NULL, &child_stdout,
139 * &child_stderr, &error);
142 * g_error ("Spawning child failed: %s", error->message);
146 * // Add a child watch function which will be called when the child process
148 * g_child_watch_add (child_pid, child_watch_cb, NULL);
150 * // You could watch for output on @child_stdout and @child_stderr using
151 * // #GUnixInputStream or #GIOChannel here.
154 * child_watch_cb (GPid pid,
156 * gpointer user_data)
158 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
159 * g_spawn_check_wait_status (status, NULL) ? "normally" : "abnormally");
161 * // Free any resources associated with the child here, such as I/O channels
162 * // on its stdout and stderr FDs. If you have no code to put in the
163 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
164 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
165 * // otherwise the child process will stay around as a zombie until this
168 * g_spawn_close_pid (pid);
174 static gint g_execute (const gchar *file,
177 gsize argv_buffer_len,
179 const gchar *search_path,
180 gchar *search_path_buffer,
181 gsize search_path_buffer_len);
183 static gboolean fork_exec (gboolean intermediate_child,
184 const gchar *working_directory,
185 const gchar * const *argv,
186 const gchar * const *envp,
187 gboolean close_descriptors,
188 gboolean search_path,
189 gboolean search_path_from_envp,
190 gboolean stdout_to_null,
191 gboolean stderr_to_null,
192 gboolean child_inherits_stdin,
193 gboolean file_and_argv_zero,
194 gboolean cloexec_pipes,
195 GSpawnChildSetupFunc child_setup,
198 gint *stdin_pipe_out,
199 gint *stdout_pipe_out,
200 gint *stderr_pipe_out,
204 const gint *source_fds,
205 const gint *target_fds,
209 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
210 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
214 * @working_directory: (type filename) (nullable): child's current working
215 * directory, or %NULL to inherit parent's
216 * @argv: (array zero-terminated=1) (element-type filename):
217 * child's argument vector
218 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
219 * child's environment, or %NULL to inherit parent's
220 * @flags: flags from #GSpawnFlags
221 * @child_setup: (scope async) (closure user_data) (nullable): function to run
222 * in the child just before `exec()`
223 * @user_data: user data for @child_setup
224 * @child_pid: (out) (optional): return location for child process reference, or %NULL
225 * @error: return location for error
227 * Executes a child program asynchronously.
229 * See g_spawn_async_with_pipes() for a full description; this function
230 * simply calls the g_spawn_async_with_pipes() without any pipes.
232 * You should call g_spawn_close_pid() on the returned child process
233 * reference when you don't need it any more.
235 * If you are writing a GTK application, and the program you are spawning is a
236 * graphical application too, then to ensure that the spawned program opens its
237 * windows on the right screen, you may want to use #GdkAppLaunchContext,
238 * #GAppLaunchContext, or set the %DISPLAY environment variable.
240 * Note that the returned @child_pid on Windows is a handle to the child
241 * process and not its identifier. Process handles and process identifiers
242 * are different concepts on Windows.
244 * Returns: %TRUE on success, %FALSE if error is set
247 g_spawn_async (const gchar *working_directory,
251 GSpawnChildSetupFunc child_setup,
256 return g_spawn_async_with_pipes (working_directory,
266 /* Avoids a danger in threaded situations (calling close()
267 * on a file descriptor twice, and another thread has
268 * re-opened it since the first close)
270 * This function is called between fork() and exec() and hence must be
271 * async-signal-safe (see signal-safety(7)).
274 close_and_invalidate (gint *fd)
283 /* Some versions of OS X define READ_OK in public headers */
288 READ_FAILED = 0, /* FALSE */
294 read_data (GString *str,
302 bytes = read (fd, buf, 4096);
308 g_string_append_len (str, buf, bytes);
311 else if (errno == EINTR)
320 _("Failed to read data from child process (%s)"),
329 * @working_directory: (type filename) (nullable): child's current working
330 * directory, or %NULL to inherit parent's
331 * @argv: (array zero-terminated=1) (element-type filename):
332 * child's argument vector, which must be non-empty and %NULL-terminated
333 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
334 * child's environment, or %NULL to inherit parent's
335 * @flags: flags from #GSpawnFlags
336 * @child_setup: (scope call) (closure user_data) (nullable): function to run
337 * in the child just before `exec()`
338 * @user_data: user data for @child_setup
339 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
340 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
341 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid(), or %NULL
342 * @error: return location for error, or %NULL
344 * Executes a child synchronously (waits for the child to exit before returning).
346 * All output from the child is stored in @standard_output and @standard_error,
347 * if those parameters are non-%NULL. Note that you must set the
348 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
349 * passing %NULL for @standard_output and @standard_error.
351 * If @wait_status is non-%NULL, the platform-specific status of
352 * the child is stored there; see the documentation of
353 * g_spawn_check_wait_status() for how to use and interpret this.
354 * On Unix platforms, note that it is usually not equal
355 * to the integer passed to `exit()` or returned from `main()`.
357 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
358 * @flags, and on POSIX platforms, the same restrictions as for
359 * g_child_watch_source_new() apply.
361 * If an error occurs, no data is returned in @standard_output,
362 * @standard_error, or @wait_status.
364 * This function calls g_spawn_async_with_pipes() internally; see that
365 * function for full details on the other parameters and details on
366 * how these functions work on Windows.
368 * Returns: %TRUE on success, %FALSE if an error was set
371 g_spawn_sync (const gchar *working_directory,
375 GSpawnChildSetupFunc child_setup,
377 gchar **standard_output,
378 gchar **standard_error,
386 GString *outstr = NULL;
387 GString *errstr = NULL;
391 g_return_val_if_fail (argv != NULL, FALSE);
392 g_return_val_if_fail (argv[0] != NULL, FALSE);
393 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
394 g_return_val_if_fail (standard_output == NULL ||
395 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
396 g_return_val_if_fail (standard_error == NULL ||
397 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
399 /* Just to ensure segfaults if callers try to use
400 * these when an error is reported.
403 *standard_output = NULL;
406 *standard_error = NULL;
408 if (!fork_exec (FALSE,
410 (const gchar * const *) argv,
411 (const gchar * const *) envp,
412 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
413 (flags & G_SPAWN_SEARCH_PATH) != 0,
414 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
415 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
416 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
417 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
418 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
419 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
424 standard_output ? &outpipe : NULL,
425 standard_error ? &errpipe : NULL,
431 /* Read data from child. */
437 outstr = g_string_new (NULL);
442 errstr = g_string_new (NULL);
445 /* Read data until we get EOF on both pipes. */
450 /* Any negative FD in the array is ignored, so we can use a fixed length.
451 * We can use UNIX FDs here without worrying about Windows HANDLEs because
452 * the Windows implementation is entirely in gspawn-win32.c. */
455 { outpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
456 { errpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
459 ret = g_poll (fds, G_N_ELEMENTS (fds), -1 /* no timeout */);
473 _("Unexpected error in reading data from a child process (%s)"),
479 if (outpipe >= 0 && fds[0].revents != 0)
481 switch (read_data (outstr, outpipe, error))
487 close_and_invalidate (&outpipe);
498 if (errpipe >= 0 && fds[1].revents != 0)
500 switch (read_data (errstr, errpipe, error))
506 close_and_invalidate (&errpipe);
518 /* These should only be open still if we had an error. */
521 close_and_invalidate (&outpipe);
523 close_and_invalidate (&errpipe);
525 /* Wait for child to exit, even if we have
530 ret = waitpid (pid, &status, 0);
536 else if (errno == ECHILD)
540 g_warning ("In call to g_spawn_sync(), wait 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.");
544 /* We don't need the wait status. */
549 if (!failed) /* avoid error pileups */
558 _("Unexpected error in waitpid() (%s)"),
567 g_string_free (outstr, TRUE);
569 g_string_free (errstr, TRUE);
576 *wait_status = status;
579 *standard_output = g_string_free (outstr, FALSE);
582 *standard_error = g_string_free (errstr, FALSE);
589 * g_spawn_async_with_pipes:
590 * @working_directory: (type filename) (nullable): child's current working
591 * directory, or %NULL to inherit parent's, in the GLib file name encoding
592 * @argv: (array zero-terminated=1) (element-type filename): child's argument
593 * vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
594 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
595 * child's environment, or %NULL to inherit parent's, in the GLib file
597 * @flags: flags from #GSpawnFlags
598 * @child_setup: (scope async) (closure user_data) (nullable): function to run
599 * in the child just before `exec()`
600 * @user_data: user data for @child_setup
601 * @child_pid: (out) (optional): return location for child process ID, or %NULL
602 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
603 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
604 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
605 * @error: return location for error
607 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
608 * so no FD assignments are used.
610 * Returns: %TRUE on success, %FALSE if an error was set
613 g_spawn_async_with_pipes (const gchar *working_directory,
617 GSpawnChildSetupFunc child_setup,
620 gint *standard_input,
621 gint *standard_output,
622 gint *standard_error,
625 return g_spawn_async_with_pipes_and_fds (working_directory,
626 (const gchar * const *) argv,
627 (const gchar * const *) envp,
629 child_setup, user_data,
640 * g_spawn_async_with_pipes_and_fds:
641 * @working_directory: (type filename) (nullable): child's current working
642 * directory, or %NULL to inherit parent's, in the GLib file name encoding
643 * @argv: (array zero-terminated=1) (element-type filename): child's argument
644 * vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
645 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
646 * child's environment, or %NULL to inherit parent's, in the GLib file
648 * @flags: flags from #GSpawnFlags
649 * @child_setup: (scope async) (closure user_data) (nullable): function to run
650 * in the child just before `exec()`
651 * @user_data: user data for @child_setup
652 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
653 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
654 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
655 * @source_fds: (array length=n_fds) (nullable): array of FDs from the parent
656 * process to make available in the child process
657 * @target_fds: (array length=n_fds) (nullable): array of FDs to remap
658 * @source_fds to in the child process
659 * @n_fds: number of FDs in @source_fds and @target_fds
660 * @child_pid_out: (out) (optional): return location for child process ID, or %NULL
661 * @stdin_pipe_out: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
662 * @stdout_pipe_out: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
663 * @stderr_pipe_out: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
664 * @error: return location for error
666 * Executes a child program asynchronously (your program will not
667 * block waiting for the child to exit).
669 * The child program is specified by the only argument that must be
670 * provided, @argv. @argv should be a %NULL-terminated array of strings,
671 * to be passed as the argument vector for the child. The first string
672 * in @argv is of course the name of the program to execute. By default,
673 * the name of the program must be a full path. If @flags contains the
674 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is used to
675 * search for the executable. If @flags contains the
676 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from @envp
677 * is used to search for the executable. If both the
678 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags are
679 * set, the `PATH` variable from @envp takes precedence over the
680 * environment variable.
682 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag
683 * is not used, then the program will be run from the current directory
684 * (or @working_directory, if specified); this might be unexpected or even
685 * dangerous in some cases when the current directory is world-writable.
687 * On Windows, note that all the string or string vector arguments to
688 * this function and the other `g_spawn*()` functions are in UTF-8, the
689 * GLib file name encoding. Unicode characters that are not part of
690 * the system codepage passed in these arguments will be correctly
691 * available in the spawned program only if it uses wide character API
692 * to retrieve its command line. For C programs built with Microsoft's
693 * tools it is enough to make the program have a `wmain()` instead of
694 * `main()`. `wmain()` has a wide character argument vector as parameter.
696 * At least currently, mingw doesn't support `wmain()`, so if you use
697 * mingw to develop the spawned program, it should call
698 * g_win32_get_command_line() to get arguments in UTF-8.
700 * On Windows the low-level child process creation API `CreateProcess()`
701 * doesn't use argument vectors, but a command line. The C runtime
702 * library's `spawn*()` family of functions (which g_spawn_async_with_pipes()
703 * eventually calls) paste the argument vector elements together into
704 * a command line, and the C runtime startup code does a corresponding
705 * reconstruction of an argument vector from the command line, to be
706 * passed to `main()`. Complications arise when you have argument vector
707 * elements that contain spaces or double quotes. The `spawn*()` functions
708 * don't do any quoting or escaping, but on the other hand the startup
709 * code does do unquoting and unescaping in order to enable receiving
710 * arguments with embedded spaces or double quotes. To work around this
711 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
712 * argument vector elements that need it before calling the C runtime
713 * `spawn()` function.
715 * The returned @child_pid on Windows is a handle to the child
716 * process, not its identifier. Process handles and process
717 * identifiers are different concepts on Windows.
719 * @envp is a %NULL-terminated array of strings, where each string
720 * has the form `KEY=VALUE`. This will become the child's environment.
721 * If @envp is %NULL, the child inherits its parent's environment.
723 * @flags should be the bitwise OR of any flags you want to affect the
724 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
725 * child will not automatically be reaped; you must use a child watch
726 * (g_child_watch_add()) to be notified about the death of the child process,
727 * otherwise it will stay around as a zombie process until this process exits.
728 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
729 * free resources which may be associated with the child process. (On Unix,
730 * using a child watch is equivalent to calling waitpid() or handling
731 * the `SIGCHLD` signal manually. On Windows, calling g_spawn_close_pid()
732 * is equivalent to calling `CloseHandle()` on the process handle returned
733 * in @child_pid). See g_child_watch_add().
735 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
736 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
737 * other open file descriptors will be inherited by the child; otherwise all
738 * descriptors except stdin/stdout/stderr will be closed before calling `exec()`
739 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
740 * absolute path, it will be looked for in the `PATH` environment
741 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
742 * absolute path, it will be looked for in the `PATH` variable from
743 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
744 * are used, the value from @envp takes precedence over the environment.
746 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
747 * standard input (by default, the child's standard input is attached to
748 * `/dev/null`). %G_SPAWN_STDIN_FROM_DEV_NULL explicitly imposes the default
749 * behavior. Both flags cannot be enabled at the same time and, in both cases,
750 * the @stdin_pipe_out argument is ignored.
752 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
753 * will be discarded (by default, it goes to the same location as the parent's
754 * standard output). %G_SPAWN_CHILD_INHERITS_STDOUT explicitly imposes the
755 * default behavior. Both flags cannot be enabled at the same time and, in
756 * both cases, the @stdout_pipe_out argument is ignored.
758 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
759 * will be discarded (by default, it goes to the same location as the parent's
760 * standard error). %G_SPAWN_CHILD_INHERITS_STDERR explicitly imposes the
761 * default behavior. Both flags cannot be enabled at the same time and, in
762 * both cases, the @stderr_pipe_out argument is ignored.
764 * It is valid to pass the same FD in multiple parameters (e.g. you can pass
765 * a single FD for both @stdout_fd and @stderr_fd, and include it in
768 * @source_fds and @target_fds allow zero or more FDs from this process to be
769 * remapped to different FDs in the spawned process. If @n_fds is greater than
770 * zero, @source_fds and @target_fds must both be non-%NULL and the same length.
771 * Each FD in @source_fds is remapped to the FD number at the same index in
772 * @target_fds. The source and target FD may be equal to simply propagate an FD
773 * to the spawned process. FD remappings are processed after standard FDs, so
774 * any target FDs which equal @stdin_fd, @stdout_fd or @stderr_fd will overwrite
775 * them in the spawned process.
777 * @source_fds is supported on Windows since 2.72.
779 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
780 * the file to execute, while the remaining elements are the actual
781 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
782 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
784 * @child_setup and @user_data are a function and user data. On POSIX
785 * platforms, the function is called in the child after GLib has
786 * performed all the setup it plans to perform (including creating
787 * pipes, closing file descriptors, etc.) but before calling `exec()`.
788 * That is, @child_setup is called just before calling `exec()` in the
789 * child. Obviously actions taken in this function will only affect
790 * the child, not the parent.
792 * On Windows, there is no separate `fork()` and `exec()` functionality.
793 * Child processes are created and run with a single API call,
794 * `CreateProcess()`. There is no sensible thing @child_setup
795 * could be used for on Windows so it is ignored and not called.
797 * If non-%NULL, @child_pid will on Unix be filled with the child's
798 * process ID. You can use the process ID to send signals to the child,
799 * or to use g_child_watch_add() (or `waitpid()`) if you specified the
800 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
801 * filled with a handle to the child process only if you specified the
802 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
803 * process using the Win32 API, for example wait for its termination
804 * with the `WaitFor*()` functions, or examine its exit code with
805 * `GetExitCodeProcess()`. You should close the handle with `CloseHandle()`
806 * or g_spawn_close_pid() when you no longer need it.
808 * If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out
809 * locations will be filled with file descriptors for writing to the child's
810 * standard input or reading from its standard output or standard error.
811 * The caller of g_spawn_async_with_pipes() must close these file descriptors
812 * when they are no longer in use. If these parameters are %NULL, the
813 * corresponding pipe won't be created.
815 * If @stdin_pipe_out is %NULL, the child's standard input is attached to
816 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
818 * If @stderr_pipe_out is NULL, the child's standard error goes to the same
819 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
822 * If @stdout_pipe_out is NULL, the child's standard output goes to the same
823 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
826 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
827 * If an error is set, the function returns %FALSE. Errors are reported
828 * even if they occur in the child (for example if the executable in
829 * `@argv[0]` is not found). Typically the `message` field of returned
830 * errors should be displayed to users. Possible errors are those from
831 * the %G_SPAWN_ERROR domain.
833 * If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out,
834 * and @stderr_pipe_out will not be filled with valid values.
836 * If @child_pid is not %NULL and an error does not occur then the returned
837 * process reference must be closed using g_spawn_close_pid().
839 * On modern UNIX platforms, GLib can use an efficient process launching
840 * codepath driven internally by `posix_spawn()`. This has the advantage of
841 * avoiding the fork-time performance costs of cloning the parent process
842 * address space, and avoiding associated memory overcommit checks that are
843 * not relevant in the context of immediately executing a distinct process.
844 * This optimized codepath will be used provided that the following conditions
847 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
848 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
849 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
850 * 4. @working_directory is %NULL
851 * 5. @child_setup is %NULL
852 * 6. The program is of a recognised binary format, or has a shebang.
853 * Otherwise, GLib will have to execute the program through the
854 * shell, which is not done using the optimized codepath.
856 * If you are writing a GTK application, and the program you are spawning is a
857 * graphical application too, then to ensure that the spawned program opens its
858 * windows on the right screen, you may want to use #GdkAppLaunchContext,
859 * #GAppLaunchContext, or set the `DISPLAY` environment variable.
861 * Returns: %TRUE on success, %FALSE if an error was set
866 g_spawn_async_with_pipes_and_fds (const gchar *working_directory,
867 const gchar * const *argv,
868 const gchar * const *envp,
870 GSpawnChildSetupFunc child_setup,
875 const gint *source_fds,
876 const gint *target_fds,
879 gint *stdin_pipe_out,
880 gint *stdout_pipe_out,
881 gint *stderr_pipe_out,
884 g_return_val_if_fail (argv != NULL, FALSE);
885 g_return_val_if_fail (argv[0] != NULL, FALSE);
886 /* canāt both inherit and set pipes to /dev/null */
887 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDIN) != INHERITS_OR_NULL_STDIN, FALSE);
888 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDOUT) != INHERITS_OR_NULL_STDOUT, FALSE);
889 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDERR) != INHERITS_OR_NULL_STDERR, FALSE);
890 /* canāt use pipes and stdin/stdout/stderr FDs */
891 g_return_val_if_fail (stdin_pipe_out == NULL || stdin_fd < 0, FALSE);
892 g_return_val_if_fail (stdout_pipe_out == NULL || stdout_fd < 0, FALSE);
893 g_return_val_if_fail (stderr_pipe_out == NULL || stderr_fd < 0, FALSE);
895 if ((flags & INHERITS_OR_NULL_STDIN) != 0)
896 stdin_pipe_out = NULL;
897 if ((flags & INHERITS_OR_NULL_STDOUT) != 0)
898 stdout_pipe_out = NULL;
899 if ((flags & INHERITS_OR_NULL_STDERR) != 0)
900 stderr_pipe_out = NULL;
902 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
904 (const gchar * const *) argv,
905 (const gchar * const *) envp,
906 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
907 (flags & G_SPAWN_SEARCH_PATH) != 0,
908 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
909 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
910 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
911 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
912 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
913 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
930 * g_spawn_async_with_fds:
931 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
932 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding;
933 * it must be non-empty and %NULL-terminated
934 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
935 * @flags: flags from #GSpawnFlags
936 * @child_setup: (scope async) (closure user_data) (nullable): function to run
937 * in the child just before `exec()`
938 * @user_data: user data for @child_setup
939 * @child_pid: (out) (optional): return location for child process ID, or %NULL
940 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
941 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
942 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
943 * @error: return location for error
945 * Executes a child program asynchronously.
947 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
948 * so no FD assignments are used.
950 * Returns: %TRUE on success, %FALSE if an error was set
955 g_spawn_async_with_fds (const gchar *working_directory,
959 GSpawnChildSetupFunc child_setup,
967 g_return_val_if_fail (argv != NULL, FALSE);
968 g_return_val_if_fail (argv[0] != NULL, FALSE);
969 g_return_val_if_fail (stdout_fd < 0 ||
970 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
971 g_return_val_if_fail (stderr_fd < 0 ||
972 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
973 /* can't inherit stdin if we have an input pipe. */
974 g_return_val_if_fail (stdin_fd < 0 ||
975 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
977 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
979 (const gchar * const *) argv,
980 (const gchar * const *) envp,
981 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
982 (flags & G_SPAWN_SEARCH_PATH) != 0,
983 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
984 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
985 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
986 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
987 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
988 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
1001 * g_spawn_command_line_sync:
1002 * @command_line: (type filename): a command line
1003 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
1004 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
1005 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid()
1006 * @error: return location for errors
1008 * A simple version of g_spawn_sync() with little-used parameters
1009 * removed, taking a command line instead of an argument vector.
1011 * See g_spawn_sync() for full details.
1013 * The @command_line argument will be parsed by g_shell_parse_argv().
1015 * Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag is enabled.
1016 * Note that %G_SPAWN_SEARCH_PATH can have security implications, so
1017 * consider using g_spawn_sync() directly if appropriate.
1019 * Possible errors are those from g_spawn_sync() and those
1020 * from g_shell_parse_argv().
1022 * If @wait_status is non-%NULL, the platform-specific status of
1023 * the child is stored there; see the documentation of
1024 * g_spawn_check_wait_status() for how to use and interpret this.
1025 * On Unix platforms, note that it is usually not equal
1026 * to the integer passed to `exit()` or returned from `main()`.
1028 * On Windows, please note the implications of g_shell_parse_argv()
1029 * parsing @command_line. Parsing is done according to Unix shell rules, not
1030 * Windows command interpreter rules.
1031 * Space is a separator, and backslashes are
1032 * special. Thus you cannot simply pass a @command_line containing
1033 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
1034 * the backslashes will be eaten, and the space will act as a
1035 * separator. You need to enclose such paths with single quotes, like
1036 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
1038 * Returns: %TRUE on success, %FALSE if an error was set
1041 g_spawn_command_line_sync (const gchar *command_line,
1042 gchar **standard_output,
1043 gchar **standard_error,
1048 gchar **argv = NULL;
1050 g_return_val_if_fail (command_line != NULL, FALSE);
1052 /* This will return a runtime error if @command_line is the empty string. */
1053 if (!g_shell_parse_argv (command_line,
1058 retval = g_spawn_sync (NULL,
1061 G_SPAWN_SEARCH_PATH,
1074 * g_spawn_command_line_async:
1075 * @command_line: (type filename): a command line
1076 * @error: return location for errors
1078 * A simple version of g_spawn_async() that parses a command line with
1079 * g_shell_parse_argv() and passes it to g_spawn_async().
1081 * Runs a command line in the background. Unlike g_spawn_async(), the
1082 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
1083 * that %G_SPAWN_SEARCH_PATH can have security implications, so
1084 * consider using g_spawn_async() directly if appropriate. Possible
1085 * errors are those from g_shell_parse_argv() and g_spawn_async().
1087 * The same concerns on Windows apply as for g_spawn_command_line_sync().
1089 * Returns: %TRUE on success, %FALSE if error is set
1092 g_spawn_command_line_async (const gchar *command_line,
1096 gchar **argv = NULL;
1098 g_return_val_if_fail (command_line != NULL, FALSE);
1100 /* This will return a runtime error if @command_line is the empty string. */
1101 if (!g_shell_parse_argv (command_line,
1106 retval = g_spawn_async (NULL,
1109 G_SPAWN_SEARCH_PATH,
1120 * g_spawn_check_wait_status:
1121 * @wait_status: A platform-specific wait status as returned from g_spawn_sync()
1124 * Set @error if @wait_status indicates the child exited abnormally
1125 * (e.g. with a nonzero exit code, or via a fatal signal).
1127 * The g_spawn_sync() and g_child_watch_add() family of APIs return the
1128 * status of subprocesses encoded in a platform-specific way.
1129 * On Unix, this is guaranteed to be in the same format waitpid() returns,
1130 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
1132 * Prior to the introduction of this function in GLib 2.34, interpreting
1133 * @wait_status required use of platform-specific APIs, which is problematic
1134 * for software using GLib as a cross-platform layer.
1136 * Additionally, many programs simply want to determine whether or not
1137 * the child exited successfully, and either propagate a #GError or
1138 * print a message to standard error. In that common case, this function
1139 * can be used. Note that the error message in @error will contain
1140 * human-readable information about the wait status.
1142 * The @domain and @code of @error have special semantics in the case
1143 * where the process has an "exit code", as opposed to being killed by
1144 * a signal. On Unix, this happens if WIFEXITED() would be true of
1145 * @wait_status. On Windows, it is always the case.
1147 * The special semantics are that the actual exit code will be the
1148 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1149 * This allows you to differentiate between different exit codes.
1151 * If the process was terminated by some means other than an exit
1152 * status (for example if it was killed by a signal), the domain will be
1153 * %G_SPAWN_ERROR and the code will be %G_SPAWN_ERROR_FAILED.
1155 * This function just offers convenience; you can of course also check
1156 * the available platform via a macro such as %G_OS_UNIX, and use
1157 * WIFEXITED() and WEXITSTATUS() on @wait_status directly. Do not attempt
1158 * to scan or parse the error message string; it may be translated and/or
1159 * change in future versions of GLib.
1161 * Prior to version 2.70, g_spawn_check_exit_status() provides the same
1162 * functionality, although under a misleading name.
1164 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1165 * @error will be set)
1170 g_spawn_check_wait_status (gint wait_status,
1173 gboolean ret = FALSE;
1175 if (WIFEXITED (wait_status))
1177 if (WEXITSTATUS (wait_status) != 0)
1179 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (wait_status),
1180 _("Child process exited with code %ld"),
1181 (long) WEXITSTATUS (wait_status));
1185 else if (WIFSIGNALED (wait_status))
1187 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1188 _("Child process killed by signal %ld"),
1189 (long) WTERMSIG (wait_status));
1192 else if (WIFSTOPPED (wait_status))
1194 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1195 _("Child process stopped by signal %ld"),
1196 (long) WSTOPSIG (wait_status));
1201 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1202 _("Child process exited abnormally"));
1212 * g_spawn_check_exit_status:
1213 * @wait_status: A status as returned from g_spawn_sync()
1216 * An old name for g_spawn_check_wait_status(), deprecated because its
1217 * name is misleading.
1219 * Despite the name of the function, @wait_status must be the wait status
1220 * as returned by g_spawn_sync(), g_subprocess_get_status(), `waitpid()`,
1221 * etc. On Unix platforms, it is incorrect for it to be the exit status
1222 * as passed to `exit()` or returned by g_subprocess_get_exit_status() or
1225 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1226 * @error will be set)
1230 * Deprecated: 2.70: Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.
1233 g_spawn_check_exit_status (gint wait_status,
1236 return g_spawn_check_wait_status (wait_status, error);
1239 /* This function is called between fork() and exec() and hence must be
1240 * async-signal-safe (see signal-safety(7)). */
1242 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1244 gchar *buf = (gchar *) vbuf;
1246 while (to_write > 0)
1248 gssize count = write (fd, buf, to_write);
1264 /* This function is called between fork() and exec() and hence must be
1265 * async-signal-safe (see signal-safety(7)). */
1268 write_err_and_exit (gint fd, gint msg)
1272 write_all (fd, &msg, sizeof(msg));
1273 write_all (fd, &en, sizeof(en));
1278 /* This function is called between fork() and exec() and hence must be
1279 * async-signal-safe (see signal-safety(7)). */
1281 set_cloexec (void *data, gint fd)
1283 if (fd >= GPOINTER_TO_INT (data))
1284 fcntl (fd, F_SETFD, FD_CLOEXEC);
1289 /* This function is called between fork() and exec() and hence must be
1290 * async-signal-safe (see signal-safety(7)). */
1292 unset_cloexec (int fd)
1297 flags = fcntl (fd, F_GETFD, 0);
1302 flags &= (~FD_CLOEXEC);
1305 result = fcntl (fd, F_SETFD, flags);
1308 while (result == -1 && errsv == EINTR);
1312 /* This function is called between fork() and exec() and hence must be
1313 * async-signal-safe (see signal-safety(7)). */
1315 dupfd_cloexec (int old_fd, int new_fd_min)
1318 #ifdef F_DUPFD_CLOEXEC
1321 fd = fcntl (old_fd, F_DUPFD_CLOEXEC, new_fd_min);
1324 while (fd == -1 && errsv == EINTR);
1326 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
1327 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
1332 fd = fcntl (old_fd, F_DUPFD, new_fd_min);
1335 while (fd == -1 && errsv == EINTR);
1336 flags = fcntl (fd, F_GETFD, 0);
1339 flags |= FD_CLOEXEC;
1342 result = fcntl (fd, F_SETFD, flags);
1345 while (result == -1 && errsv == EINTR);
1351 /* fdwalk()-compatible callback to close a fd for non-compliant
1352 * implementations of fdwalk() that potentially pass already
1355 * It is not an error to pass an invalid fd to this function.
1357 * This function is called between fork() and exec() and hence must be
1358 * async-signal-safe (see signal-safety(7)).
1360 G_GNUC_UNUSED static int
1361 close_func_with_invalid_fds (void *data, int fd)
1363 /* We use close and not g_close here because on some platforms, we
1364 * don't know how to close only valid, open file descriptors, so we
1365 * have to pass bad fds to close too. g_close warns if given a bad
1368 * This function returns no error, because there is nothing that the caller
1369 * could do with that information. That is even the case for EINTR. See
1370 * g_close() about the specialty of EINTR and why that is correct.
1371 * If g_close() ever gets extended to handle EINTR specially, then this place
1372 * should get updated to do the same handling.
1374 if (fd >= GPOINTER_TO_INT (data))
1381 struct linux_dirent64
1383 guint64 d_ino; /* 64-bit inode number */
1384 guint64 d_off; /* 64-bit offset to next structure */
1385 unsigned short d_reclen; /* Size of this dirent */
1386 unsigned char d_type; /* File type */
1387 char d_name[]; /* Filename (null-terminated) */
1390 /* This function is called between fork() and exec() and hence must be
1391 * async-signal-safe (see signal-safety(7)). */
1393 filename_to_fd (const char *p)
1397 const int cutoff = G_MAXINT / 10;
1398 const int cutlim = G_MAXINT % 10;
1403 while ((c = *p++) != '\0')
1405 if (c < '0' || c > '9')
1409 /* Check for overflow. */
1410 if (fd > cutoff || (fd == cutoff && c > cutlim))
1420 static int safe_fdwalk_with_invalid_fds (int (*cb)(void *data, int fd), void *data);
1422 /* This function is called between fork() and exec() and hence must be
1423 * async-signal-safe (see signal-safety(7)). */
1425 safe_fdwalk (int (*cb)(void *data, int fd), void *data)
1428 /* Use fdwalk function provided by the system if it is known to be
1429 * async-signal safe.
1431 * Currently there are no operating systems known to provide a safe
1432 * implementation, so this section is not used for now.
1434 return fdwalk (cb, data);
1436 /* Fallback implementation of fdwalk. It should be async-signal safe, but it
1437 * may fail on non-Linux operating systems. See safe_fdwalk_with_invalid_fds
1438 * for a slower alternative.
1445 /* Avoid use of opendir/closedir since these are not async-signal-safe. */
1446 int dir_fd = open ("/proc/self/fd", O_RDONLY | O_DIRECTORY);
1449 /* buf needs to be aligned correctly to receive linux_dirent64.
1450 * C11 has _Alignof for this purpose, but for now a
1451 * union serves the same purpose. */
1455 struct linux_dirent64 alignment;
1458 struct linux_dirent64 *de;
1460 while ((nread = syscall (SYS_getdents64, dir_fd, u.buf, sizeof (u.buf))) > 0)
1462 for (pos = 0; pos < nread; pos += de->d_reclen)
1464 de = (struct linux_dirent64 *) (u.buf + pos);
1466 fd = filename_to_fd (de->d_name);
1467 if (fd < 0 || fd == dir_fd)
1470 if ((res = cb (data, fd)) != 0)
1475 g_close (dir_fd, NULL);
1479 /* If /proc is not mounted or not accessible we fail here and rely on
1480 * safe_fdwalk_with_invalid_fds to fall back to the old
1485 #if defined(__sun__) && defined(F_PREVFD) && defined(F_NEXTFD)
1487 * Solaris 11.4 has a signal-safe way which allows
1488 * us to find all file descriptors in a process.
1490 * fcntl(fd, F_NEXTFD, maxfd)
1491 * - returns the first allocated file descriptor <= maxfd > fd.
1493 * fcntl(fd, F_PREVFD)
1494 * - return highest allocated file descriptor < fd.
1499 open_max = fcntl (INT_MAX, F_PREVFD); /* find the maximum fd */
1500 if (open_max < 0) /* No open files */
1503 for (fd = -1; (fd = fcntl (fd, F_NEXTFD, open_max)) != -1; )
1504 if ((res = cb (data, fd)) != 0 || fd == open_max)
1510 return safe_fdwalk_with_invalid_fds (cb, data);
1514 /* This function is called between fork() and exec() and hence must be
1515 * async-signal-safe (see signal-safety(7)). */
1517 safe_fdwalk_with_invalid_fds (int (*cb)(void *data, int fd), void *data)
1519 /* Fallback implementation of fdwalk. It should be async-signal safe, but it
1520 * may be slow, especially on systems allowing very high number of open file
1527 #if 0 && defined(HAVE_SYS_RESOURCE_H)
1530 /* Use getrlimit() function provided by the system if it is known to be
1531 * async-signal safe.
1533 * Currently there are no operating systems known to provide a safe
1534 * implementation, so this section is not used for now.
1536 if (getrlimit (RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1537 open_max = rl.rlim_max;
1539 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1540 /* Use sysconf() function provided by the system if it is known to be
1541 * async-signal safe.
1543 * FreeBSD: sysconf() is included in the list of async-signal safe functions
1544 * found in https://man.freebsd.org/sigaction(2).
1546 * OpenBSD: sysconf() is included in the list of async-signal safe functions
1547 * found in https://man.openbsd.org/sigaction.2.
1549 * Apple: sysconf() is included in the list of async-signal safe functions
1550 * found in https://opensource.apple.com/source/xnu/xnu-517.12.7/bsd/man/man2/sigaction.2
1553 open_max = sysconf (_SC_OPEN_MAX);
1555 /* Hardcoded fallback: the default process hard limit in Linux as of 2020 */
1559 #if defined(__APPLE__)
1560 /* proc_pidinfo isn't documented as async-signal-safe but looking at the implementation
1561 * in the darwin tree here:
1563 * https://opensource.apple.com/source/Libc/Libc-498/darwin/libproc.c.auto.html
1565 * It's just a thin wrapper around a syscall, so it's probably okay.
1568 char buffer[4096 * PROC_PIDLISTFD_SIZE];
1569 ssize_t buffer_size;
1571 buffer_size = proc_pidinfo (getpid (), PROC_PIDLISTFDS, 0, buffer, sizeof (buffer));
1573 if (buffer_size > 0 &&
1574 sizeof (buffer) >= (size_t) buffer_size &&
1575 (buffer_size % PROC_PIDLISTFD_SIZE) == 0)
1577 const struct proc_fdinfo *fd_info = (const struct proc_fdinfo *) buffer;
1578 size_t number_of_fds = (size_t) buffer_size / PROC_PIDLISTFD_SIZE;
1580 for (size_t i = 0; i < number_of_fds; i++)
1581 if ((res = cb (data, fd_info[i].proc_fd)) != 0)
1589 for (fd = 0; fd < open_max; fd++)
1590 if ((res = cb (data, fd)) != 0)
1596 /* This function is called between fork() and exec() and hence must be
1597 * async-signal-safe (see signal-safety(7)). */
1599 safe_fdwalk_set_cloexec (int lowfd)
1603 #if defined(HAVE_CLOSE_RANGE) && defined(CLOSE_RANGE_CLOEXEC)
1604 /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1605 * around the same time. It was designed for use in async-signal-safe
1606 * situations: https://bugs.python.org/issue38061
1608 * The `CLOSE_RANGE_CLOEXEC` flag was added in Linux 5.11, and is not yet
1609 * present in FreeBSD.
1611 * Handle ENOSYS in case itās supported in libc but not the kernel; if so,
1612 * fall back to safe_fdwalk(). Handle EINVAL in case `CLOSE_RANGE_CLOEXEC`
1613 * is not supported. */
1614 ret = close_range (lowfd, G_MAXUINT, CLOSE_RANGE_CLOEXEC);
1615 if (ret == 0 || !(errno == ENOSYS || errno == EINVAL))
1617 #endif /* HAVE_CLOSE_RANGE */
1619 ret = safe_fdwalk (set_cloexec, GINT_TO_POINTER (lowfd));
1624 /* This function is called between fork() and exec() and hence must be
1625 * async-signal-safe (see signal-safety(7)).
1627 * On failure, `-1` will be returned and errno will be set. */
1629 safe_closefrom (int lowfd)
1633 #if defined(HAVE_CLOSE_RANGE)
1634 /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1635 * around the same time. It was designed for use in async-signal-safe
1636 * situations: https://bugs.python.org/issue38061
1638 * Handle ENOSYS in case itās supported in libc but not the kernel; if so,
1639 * fall back to safe_fdwalk(). */
1640 ret = close_range (lowfd, G_MAXUINT, 0);
1641 if (ret == 0 || errno != ENOSYS)
1643 #endif /* HAVE_CLOSE_RANGE */
1645 #if defined(__FreeBSD__) || defined(__OpenBSD__) || \
1646 (defined(__sun__) && defined(F_CLOSEFROM))
1647 /* Use closefrom function provided by the system if it is known to be
1648 * async-signal safe.
1650 * FreeBSD: closefrom is included in the list of async-signal safe functions
1651 * found in https://man.freebsd.org/sigaction(2).
1653 * OpenBSD: closefrom is not included in the list, but a direct system call
1654 * should be safe to use.
1656 * In Solaris as of 11.3 SRU 31, closefrom() is also a direct system call.
1657 * On such systems, F_CLOSEFROM is defined.
1659 (void) closefrom (lowfd);
1661 #elif defined(__DragonFly__)
1662 /* It is unclear whether closefrom function included in DragonFlyBSD libc_r
1663 * is safe to use because it calls a lot of library functions. It is also
1664 * unclear whether libc_r itself is still being used. Therefore, we do a
1665 * direct system call here ourselves to avoid possible issues.
1667 (void) syscall (SYS_closefrom, lowfd);
1669 #elif defined(F_CLOSEM)
1670 /* NetBSD and AIX have a special fcntl command which does the same thing as
1671 * closefrom. NetBSD also includes closefrom function, which seems to be a
1672 * simple wrapper of the fcntl command.
1674 return fcntl (lowfd, F_CLOSEM);
1676 ret = safe_fdwalk (close_func_with_invalid_fds, GINT_TO_POINTER (lowfd));
1682 /* This function is called between fork() and exec() and hence must be
1683 * async-signal-safe (see signal-safety(7)). */
1685 safe_dup2 (gint fd1, gint fd2)
1690 ret = dup2 (fd1, fd2);
1691 while (ret < 0 && (errno == EINTR || errno == EBUSY));
1696 /* This function is called between fork() and exec() and hence must be
1697 * async-signal-safe (see signal-safety(7)). */
1699 relocate_fd_out_of_standard_range (gint *fd)
1702 const int min_fileno = STDERR_FILENO + 1;
1705 ret = fcntl (*fd, F_DUPFD, min_fileno);
1706 while (ret < 0 && errno == EINTR);
1708 /* Note we don't need to close the old fd, because the caller is expected
1709 * to close fds in the standard range itself.
1711 if (ret >= min_fileno)
1720 /* This function is called between fork() and exec() and hence must be
1721 * async-signal-safe (see signal-safety(7)). */
1723 safe_open (const char *path, gint mode)
1728 ret = open (path, mode);
1729 while (ret < 0 && errno == EINTR);
1744 /* This function is called between fork() and exec() and hence must be
1745 * async-signal-safe (see signal-safety(7)) until it calls exec().
1747 * All callers must guarantee that @argv and @argv[0] are non-NULL. */
1749 do_exec (gint child_err_report_fd,
1754 const gint *target_fds,
1756 const gchar *working_directory,
1757 const gchar * const *argv,
1758 gchar **argv_buffer,
1759 gsize argv_buffer_len,
1760 const gchar * const *envp,
1761 gboolean close_descriptors,
1762 const gchar *search_path,
1763 gchar *search_path_buffer,
1764 gsize search_path_buffer_len,
1765 gboolean stdout_to_null,
1766 gboolean stderr_to_null,
1767 gboolean child_inherits_stdin,
1768 gboolean file_and_argv_zero,
1769 GSpawnChildSetupFunc child_setup,
1773 gint max_target_fd = 0;
1775 if (working_directory && chdir (working_directory) < 0)
1776 write_err_and_exit (child_err_report_fd,
1777 CHILD_CHDIR_FAILED);
1779 /* It's possible the caller assigned stdin to an fd with a
1780 * file number that is supposed to be reserved for
1783 * If so, move it up out of the standard range, so it doesn't
1786 if (IS_STD_FILENO (stdin_fd) && stdin_fd != STDIN_FILENO)
1788 int old_fd = stdin_fd;
1790 if (!relocate_fd_out_of_standard_range (&stdin_fd))
1791 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1793 if (stdout_fd == old_fd)
1794 stdout_fd = stdin_fd;
1796 if (stderr_fd == old_fd)
1797 stderr_fd = stdin_fd;
1800 /* Redirect pipes as required
1802 * There are two cases where we don't need to do the redirection
1803 * 1. Where the associated file descriptor is cleared/invalid
1804 * 2. When the associated file descriptor is already given the
1805 * correct file number.
1807 if (IS_VALID_FILENO (stdin_fd) && stdin_fd != STDIN_FILENO)
1809 if (safe_dup2 (stdin_fd, 0) < 0)
1810 write_err_and_exit (child_err_report_fd,
1811 CHILD_DUPFD_FAILED);
1813 set_cloexec (GINT_TO_POINTER(0), stdin_fd);
1815 else if (!child_inherits_stdin)
1817 /* Keep process from blocking on a read of stdin */
1818 gint read_null = safe_open ("/dev/null", O_RDONLY);
1820 write_err_and_exit (child_err_report_fd,
1822 if (safe_dup2 (read_null, 0) < 0)
1823 write_err_and_exit (child_err_report_fd,
1824 CHILD_DUPFD_FAILED);
1825 close_and_invalidate (&read_null);
1828 /* Like with stdin above, it's possible the caller assigned
1829 * stdout to an fd with a file number that's intruding on the
1832 * If so, move it out of the way, too.
1834 if (IS_STD_FILENO (stdout_fd) && stdout_fd != STDOUT_FILENO)
1836 int old_fd = stdout_fd;
1838 if (!relocate_fd_out_of_standard_range (&stdout_fd))
1839 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1841 if (stderr_fd == old_fd)
1842 stderr_fd = stdout_fd;
1845 if (IS_VALID_FILENO (stdout_fd) && stdout_fd != STDOUT_FILENO)
1847 if (safe_dup2 (stdout_fd, 1) < 0)
1848 write_err_and_exit (child_err_report_fd,
1849 CHILD_DUPFD_FAILED);
1851 set_cloexec (GINT_TO_POINTER(0), stdout_fd);
1853 else if (stdout_to_null)
1855 gint write_null = safe_open ("/dev/null", O_WRONLY);
1857 write_err_and_exit (child_err_report_fd,
1859 if (safe_dup2 (write_null, 1) < 0)
1860 write_err_and_exit (child_err_report_fd,
1861 CHILD_DUPFD_FAILED);
1862 close_and_invalidate (&write_null);
1865 if (IS_STD_FILENO (stderr_fd) && stderr_fd != STDERR_FILENO)
1867 if (!relocate_fd_out_of_standard_range (&stderr_fd))
1868 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1871 /* Like with stdin/stdout above, it's possible the caller assigned
1872 * stderr to an fd with a file number that's intruding on the
1875 * Make sure it's out of the way, also.
1877 if (IS_VALID_FILENO (stderr_fd) && stderr_fd != STDERR_FILENO)
1879 if (safe_dup2 (stderr_fd, 2) < 0)
1880 write_err_and_exit (child_err_report_fd,
1881 CHILD_DUPFD_FAILED);
1883 set_cloexec (GINT_TO_POINTER(0), stderr_fd);
1885 else if (stderr_to_null)
1887 gint write_null = safe_open ("/dev/null", O_WRONLY);
1889 write_err_and_exit (child_err_report_fd,
1891 if (safe_dup2 (write_null, 2) < 0)
1892 write_err_and_exit (child_err_report_fd,
1893 CHILD_DUPFD_FAILED);
1894 close_and_invalidate (&write_null);
1897 /* Close all file descriptors but stdin, stdout and stderr, and any of source_fds,
1898 * before we exec. Note that this includes
1899 * child_err_report_fd, which keeps the parent from blocking
1900 * forever on the other end of that pipe.
1902 if (close_descriptors)
1904 if (child_setup == NULL && n_fds == 0)
1906 if (safe_dup2 (child_err_report_fd, 3) < 0)
1907 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1908 set_cloexec (GINT_TO_POINTER (0), 3);
1909 if (safe_closefrom (4) < 0)
1910 write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1911 child_err_report_fd = 3;
1915 if (safe_fdwalk_set_cloexec (3) < 0)
1916 write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1921 /* We need to do child_err_report_fd anyway */
1922 set_cloexec (GINT_TO_POINTER (0), child_err_report_fd);
1926 * Work through the @source_fds and @target_fds mapping.
1928 * Based on code originally derived from
1929 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
1930 * used under the LGPLv2+ with permission from author. (The code has
1931 * since migrated to vte:src/spawn.cc:SpawnContext::exec and is no longer
1932 * terribly similar to what we have here.)
1937 for (i = 0; i < n_fds; i++)
1938 max_target_fd = MAX (max_target_fd, target_fds[i]);
1940 if (max_target_fd == G_MAXINT)
1943 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1946 /* If we're doing remapping fd assignments, we need to handle
1947 * the case where the user has specified e.g. 5 -> 4, 4 -> 6.
1948 * We do this by duping all source fds, taking care to ensure the new
1949 * fds are larger than any target fd to avoid introducing new conflicts.
1951 for (i = 0; i < n_fds; i++)
1953 if (source_fds[i] != target_fds[i])
1955 source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
1956 if (source_fds[i] < 0)
1957 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1961 for (i = 0; i < n_fds; i++)
1963 /* For basic fd assignments (where source == target), we can just
1966 if (source_fds[i] == target_fds[i])
1968 unset_cloexec (source_fds[i]);
1972 /* If any of the @target_fds conflict with @child_err_report_fd,
1973 * dup it so it doesnāt get conflated.
1975 if (target_fds[i] == child_err_report_fd)
1977 child_err_report_fd = dupfd_cloexec (child_err_report_fd, max_target_fd + 1);
1978 if (child_err_report_fd < 0)
1979 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1982 if (safe_dup2 (source_fds[i], target_fds[i]) < 0)
1983 write_err_and_exit (child_err_report_fd, CHILD_DUPFD_FAILED);
1985 close_and_invalidate (&source_fds[i]);
1990 /* Call user function just before we exec */
1993 (* child_setup) (user_data);
1997 (gchar **) (file_and_argv_zero ? argv + 1 : argv),
1998 argv_buffer, argv_buffer_len,
1999 (gchar **) envp, search_path, search_path_buffer, search_path_buffer_len);
2002 write_err_and_exit (child_err_report_fd,
2019 if (bytes >= sizeof(gint)*2)
2020 break; /* give up, who knows what happened, should not be
2026 ((gchar*)buf) + bytes,
2027 sizeof(gint) * n_ints_in_buf - bytes);
2028 if (chunk < 0 && errno == EINTR)
2035 /* Some weird shit happened, bail out */
2038 G_SPAWN_ERROR_FAILED,
2039 _("Failed to read from child pipe (%s)"),
2040 g_strerror (errsv));
2044 else if (chunk == 0)
2046 else /* chunk > 0 */
2050 *n_ints_read = (gint)(bytes / sizeof(gint));
2055 #ifdef POSIX_SPAWN_AVAILABLE
2057 do_posix_spawn (const gchar * const *argv,
2058 const gchar * const *envp,
2059 gboolean search_path,
2060 gboolean stdout_to_null,
2061 gboolean stderr_to_null,
2062 gboolean child_inherits_stdin,
2063 gboolean file_and_argv_zero,
2065 gint *child_close_fds,
2069 const gint *source_fds,
2070 const gint *target_fds,
2074 gint *duped_source_fds = NULL;
2075 gint max_target_fd = 0;
2076 const gchar * const *argv_pass;
2077 posix_spawnattr_t attr;
2078 posix_spawn_file_actions_t file_actions;
2079 gint parent_close_fds[3];
2080 gsize num_parent_close_fds = 0;
2081 GSList *child_close = NULL;
2087 g_assert (argv != NULL && argv[0] != NULL);
2089 if (*argv[0] == '\0')
2091 /* We check the simple case first. */
2095 r = posix_spawnattr_init (&attr);
2099 if (child_close_fds)
2102 while (child_close_fds[++i] != -1)
2103 child_close = g_slist_prepend (child_close,
2104 GINT_TO_POINTER (child_close_fds[i]));
2107 r = posix_spawnattr_setflags (&attr, POSIX_SPAWN_SETSIGDEF);
2109 goto out_free_spawnattr;
2111 /* Reset some signal handlers that we may use */
2112 sigemptyset (&mask);
2113 sigaddset (&mask, SIGCHLD);
2114 sigaddset (&mask, SIGINT);
2115 sigaddset (&mask, SIGTERM);
2116 sigaddset (&mask, SIGHUP);
2118 r = posix_spawnattr_setsigdefault (&attr, &mask);
2120 goto out_free_spawnattr;
2122 r = posix_spawn_file_actions_init (&file_actions);
2124 goto out_free_spawnattr;
2126 /* Redirect pipes as required */
2130 r = posix_spawn_file_actions_adddup2 (&file_actions, stdin_fd, 0);
2134 if (!g_slist_find (child_close, GINT_TO_POINTER (stdin_fd)))
2135 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdin_fd));
2137 else if (!child_inherits_stdin)
2139 /* Keep process from blocking on a read of stdin */
2140 gint read_null = safe_open ("/dev/null", O_RDONLY | O_CLOEXEC);
2141 g_assert (read_null != -1);
2142 parent_close_fds[num_parent_close_fds++] = read_null;
2144 #ifndef HAVE_O_CLOEXEC
2145 fcntl (read_null, F_SETFD, FD_CLOEXEC);
2148 r = posix_spawn_file_actions_adddup2 (&file_actions, read_null, 0);
2155 r = posix_spawn_file_actions_adddup2 (&file_actions, stdout_fd, 1);
2159 if (!g_slist_find (child_close, GINT_TO_POINTER (stdout_fd)))
2160 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdout_fd));
2162 else if (stdout_to_null)
2164 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
2165 g_assert (write_null != -1);
2166 parent_close_fds[num_parent_close_fds++] = write_null;
2168 #ifndef HAVE_O_CLOEXEC
2169 fcntl (write_null, F_SETFD, FD_CLOEXEC);
2172 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 1);
2179 r = posix_spawn_file_actions_adddup2 (&file_actions, stderr_fd, 2);
2183 if (!g_slist_find (child_close, GINT_TO_POINTER (stderr_fd)))
2184 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stderr_fd));
2186 else if (stderr_to_null)
2188 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
2189 g_assert (write_null != -1);
2190 parent_close_fds[num_parent_close_fds++] = write_null;
2192 #ifndef HAVE_O_CLOEXEC
2193 fcntl (write_null, F_SETFD, FD_CLOEXEC);
2196 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 2);
2201 /* If source_fds[i] != target_fds[i], we need to handle the case
2202 * where the user has specified, e.g., 5 -> 4, 4 -> 6. We do this
2203 * by duping the source fds, taking care to ensure the new fds are
2204 * larger than any target fd to avoid introducing new conflicts.
2206 * If source_fds[i] == target_fds[i], then we just need to leak
2207 * the fd into the child process, which we *could* do by temporarily
2208 * unsetting CLOEXEC and then setting it again after we spawn if
2209 * it was originally set. POSIX requires that the addup2 action unset
2210 * CLOEXEC if source and target are identical, so you'd think doing it
2211 * manually wouldn't be needed, but unfortunately as of 2021 many
2212 * libcs still don't do so. Example nonconforming libcs:
2213 * Bionic: https://android.googlesource.com/platform/bionic/+/f6e5b582604715729b09db3e36a7aeb8c24b36a4/libc/bionic/spawn.cpp#71
2214 * uclibc-ng: https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/librt/spawn.c?id=7c36bcae09d66bbaa35cbb02253ae0556f42677e#n88
2216 * Anyway, unsetting CLOEXEC ourselves would open a small race window
2217 * where the fd could be inherited into a child process if another
2218 * thread spawns something at the same time, because we have not
2219 * called fork() and are multithreaded here. This race is avoidable by
2220 * using dupfd_cloexec, which we already have to do to handle the
2221 * source_fds[i] != target_fds[i] case. So let's always do it!
2224 for (i = 0; i < n_fds; i++)
2225 max_target_fd = MAX (max_target_fd, target_fds[i]);
2227 if (max_target_fd == G_MAXINT)
2230 duped_source_fds = g_new (gint, n_fds);
2231 for (i = 0; i < n_fds; i++)
2233 duped_source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
2234 if (duped_source_fds[i] < 0)
2238 for (i = 0; i < n_fds; i++)
2240 r = posix_spawn_file_actions_adddup2 (&file_actions, duped_source_fds[i], target_fds[i]);
2245 /* Intentionally close the fds in the child as the last file action,
2246 * having been careful not to add the same fd to this list twice.
2248 * This is important to allow (e.g.) for the same fd to be passed as stdout
2249 * and stderr (we must not close it before we have dupped it in both places,
2250 * and we must not attempt to close it twice).
2252 for (elem = child_close; elem != NULL; elem = elem->next)
2254 r = posix_spawn_file_actions_addclose (&file_actions,
2255 GPOINTER_TO_INT (elem->data));
2260 argv_pass = file_and_argv_zero ? argv + 1 : argv;
2262 envp = (const gchar * const *) environ;
2264 /* Don't search when it contains a slash. */
2265 if (!search_path || strchr (argv[0], '/') != NULL)
2266 r = posix_spawn (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2268 r = posix_spawnp (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2270 if (r == 0 && child_pid != NULL)
2274 for (i = 0; i < num_parent_close_fds; i++)
2275 close_and_invalidate (&parent_close_fds [i]);
2277 if (duped_source_fds != NULL)
2279 for (i = 0; i < n_fds; i++)
2280 close_and_invalidate (&duped_source_fds[i]);
2281 g_free (duped_source_fds);
2284 posix_spawn_file_actions_destroy (&file_actions);
2286 posix_spawnattr_destroy (&attr);
2287 g_slist_free (child_close);
2291 #endif /* POSIX_SPAWN_AVAILABLE */
2294 fork_exec (gboolean intermediate_child,
2295 const gchar *working_directory,
2296 const gchar * const *argv,
2297 const gchar * const *envp,
2298 gboolean close_descriptors,
2299 gboolean search_path,
2300 gboolean search_path_from_envp,
2301 gboolean stdout_to_null,
2302 gboolean stderr_to_null,
2303 gboolean child_inherits_stdin,
2304 gboolean file_and_argv_zero,
2305 gboolean cloexec_pipes,
2306 GSpawnChildSetupFunc child_setup,
2309 gint *stdin_pipe_out,
2310 gint *stdout_pipe_out,
2311 gint *stderr_pipe_out,
2315 const gint *source_fds,
2316 const gint *target_fds,
2321 gint child_err_report_pipe[2] = { -1, -1 };
2322 gint child_pid_report_pipe[2] = { -1, -1 };
2323 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
2325 const gchar *chosen_search_path;
2326 gchar *search_path_buffer = NULL;
2327 gchar *search_path_buffer_heap = NULL;
2328 gsize search_path_buffer_len = 0;
2329 gchar **argv_buffer = NULL;
2330 gchar **argv_buffer_heap = NULL;
2331 gsize argv_buffer_len = 0;
2332 gint stdin_pipe[2] = { -1, -1 };
2333 gint stdout_pipe[2] = { -1, -1 };
2334 gint stderr_pipe[2] = { -1, -1 };
2335 gint child_close_fds[4] = { -1, -1, -1, -1 };
2336 gint n_child_close_fds = 0;
2337 gint *source_fds_copy = NULL;
2339 g_assert (argv != NULL && argv[0] != NULL);
2340 g_assert (stdin_pipe_out == NULL || stdin_fd < 0);
2341 g_assert (stdout_pipe_out == NULL || stdout_fd < 0);
2342 g_assert (stderr_pipe_out == NULL || stderr_fd < 0);
2344 /* If pipes have been requested, open them */
2345 if (stdin_pipe_out != NULL)
2347 if (!g_unix_open_pipe (stdin_pipe, pipe_flags, error))
2348 goto cleanup_and_fail;
2349 if (_g_spawn_invalid_source_fd (stdin_pipe[0], source_fds, n_fds, error) ||
2350 _g_spawn_invalid_source_fd (stdin_pipe[1], source_fds, n_fds, error))
2351 goto cleanup_and_fail;
2352 child_close_fds[n_child_close_fds++] = stdin_pipe[1];
2353 stdin_fd = stdin_pipe[0];
2356 if (stdout_pipe_out != NULL)
2358 if (!g_unix_open_pipe (stdout_pipe, pipe_flags, error))
2359 goto cleanup_and_fail;
2360 if (_g_spawn_invalid_source_fd (stdout_pipe[0], source_fds, n_fds, error) ||
2361 _g_spawn_invalid_source_fd (stdout_pipe[1], source_fds, n_fds, error))
2362 goto cleanup_and_fail;
2363 child_close_fds[n_child_close_fds++] = stdout_pipe[0];
2364 stdout_fd = stdout_pipe[1];
2367 if (stderr_pipe_out != NULL)
2369 if (!g_unix_open_pipe (stderr_pipe, pipe_flags, error))
2370 goto cleanup_and_fail;
2371 if (_g_spawn_invalid_source_fd (stderr_pipe[0], source_fds, n_fds, error) ||
2372 _g_spawn_invalid_source_fd (stderr_pipe[1], source_fds, n_fds, error))
2373 goto cleanup_and_fail;
2374 child_close_fds[n_child_close_fds++] = stderr_pipe[0];
2375 stderr_fd = stderr_pipe[1];
2378 child_close_fds[n_child_close_fds++] = -1;
2380 #ifdef POSIX_SPAWN_AVAILABLE
2381 if (!intermediate_child && working_directory == NULL && !close_descriptors &&
2382 !search_path_from_envp && child_setup == NULL)
2384 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2385 "GLib", "posix_spawn",
2388 status = do_posix_spawn (argv,
2393 child_inherits_stdin,
2406 if (status != ENOEXEC)
2410 G_SPAWN_ERROR_FAILED,
2411 _("Failed to spawn child process ā%sā (%s)"),
2413 g_strerror (status));
2414 goto cleanup_and_fail;
2417 /* posix_spawn is not intended to support script execution. It does in
2418 * some situations on some glibc versions, but that will be fixed.
2419 * So if it fails with ENOEXEC, we fall through to the regular
2420 * gspawn codepath so that script execution can be attempted,
2421 * per standard gspawn behaviour. */
2422 g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
2426 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2428 "posix_spawn avoided %s%s%s%s%s",
2429 !intermediate_child ? "" : "(automatic reaping requested) ",
2430 working_directory == NULL ? "" : "(workdir specified) ",
2431 !close_descriptors ? "" : "(fd close requested) ",
2432 !search_path_from_envp ? "" : "(using envp for search path) ",
2433 child_setup == NULL ? "" : "(child_setup specified) ");
2435 #endif /* POSIX_SPAWN_AVAILABLE */
2437 /* Choose a search path. This has to be done before calling fork()
2438 * as getenv() isnāt async-signal-safe (see `man 7 signal-safety`). */
2439 chosen_search_path = NULL;
2440 if (search_path_from_envp)
2441 chosen_search_path = g_environ_getenv ((gchar **) envp, "PATH");
2442 if (search_path && chosen_search_path == NULL)
2443 chosen_search_path = g_getenv ("PATH");
2445 if ((search_path || search_path_from_envp) && chosen_search_path == NULL)
2447 /* There is no 'PATH' in the environment. The default
2448 * * search path in libc is the current directory followed by
2449 * * the path 'confstr' returns for '_CS_PATH'.
2452 /* In GLib we put . last, for security, and don't use the
2453 * * unportable confstr(); UNIX98 does not actually specify
2454 * * what to search if PATH is unset. POSIX may, dunno.
2457 chosen_search_path = "/bin:/usr/bin:.";
2460 if (search_path || search_path_from_envp)
2461 g_assert (chosen_search_path != NULL);
2463 g_assert (chosen_search_path == NULL);
2465 /* Allocate a buffer which the fork()ed child can use to assemble potential
2466 * paths for the binary to exec(), combining the argv[0] and elements from
2467 * the chosen_search_path. This canāt be done in the child because malloc()
2468 * (or alloca()) are not async-signal-safe (see `man 7 signal-safety`).
2470 * Add 2 for the nul terminator and a leading `/`. */
2471 if (chosen_search_path != NULL)
2473 search_path_buffer_len = strlen (chosen_search_path) + strlen (argv[0]) + 2;
2474 if (search_path_buffer_len < 4000)
2476 /* Prefer small stack allocations to avoid valgrind leak warnings
2477 * in forked child. The 4000B cutoff is arbitrary. */
2478 search_path_buffer = g_alloca (search_path_buffer_len);
2482 search_path_buffer_heap = g_malloc (search_path_buffer_len);
2483 search_path_buffer = search_path_buffer_heap;
2487 if (search_path || search_path_from_envp)
2488 g_assert (search_path_buffer != NULL);
2490 g_assert (search_path_buffer == NULL);
2492 /* And allocate a buffer which is 2 elements longer than @argv, so that if
2493 * script_execute() has to be called later on, it can build a wrapper argv
2494 * array in this buffer. */
2495 argv_buffer_len = g_strv_length ((gchar **) argv) + 2;
2496 if (argv_buffer_len < 4000 / sizeof (gchar *))
2498 /* Prefer small stack allocations to avoid valgrind leak warnings
2499 * in forked child. The 4000B cutoff is arbitrary. */
2500 argv_buffer = g_newa (gchar *, argv_buffer_len);
2504 argv_buffer_heap = g_new (gchar *, argv_buffer_len);
2505 argv_buffer = argv_buffer_heap;
2508 /* And one to hold a copy of @source_fds for later manipulation in do_exec(). */
2509 source_fds_copy = g_new (int, n_fds);
2511 memcpy (source_fds_copy, source_fds, sizeof (*source_fds) * n_fds);
2513 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
2514 goto cleanup_and_fail;
2515 if (_g_spawn_invalid_source_fd (child_err_report_pipe[0], source_fds, n_fds, error) ||
2516 _g_spawn_invalid_source_fd (child_err_report_pipe[1], source_fds, n_fds, error))
2517 goto cleanup_and_fail;
2519 if (intermediate_child)
2521 if (!g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
2522 goto cleanup_and_fail;
2523 if (_g_spawn_invalid_source_fd (child_pid_report_pipe[0], source_fds, n_fds, error) ||
2524 _g_spawn_invalid_source_fd (child_pid_report_pipe[1], source_fds, n_fds, error))
2525 goto cleanup_and_fail;
2537 _("Failed to fork (%s)"),
2538 g_strerror (errsv));
2540 goto cleanup_and_fail;
2544 /* Immediate child. This may or may not be the child that
2545 * actually execs the new process.
2548 /* Reset some signal handlers that we may use */
2549 signal (SIGCHLD, SIG_DFL);
2550 signal (SIGINT, SIG_DFL);
2551 signal (SIGTERM, SIG_DFL);
2552 signal (SIGHUP, SIG_DFL);
2554 /* Be sure we crash if the parent exits
2555 * and we write to the err_report_pipe
2557 signal (SIGPIPE, SIG_DFL);
2559 /* Close the parent's end of the pipes;
2560 * not needed in the close_descriptors case,
2563 close_and_invalidate (&child_err_report_pipe[0]);
2564 close_and_invalidate (&child_pid_report_pipe[0]);
2565 if (child_close_fds[0] != -1)
2568 while (child_close_fds[++i] != -1)
2569 close_and_invalidate (&child_close_fds[i]);
2572 if (intermediate_child)
2574 /* We need to fork an intermediate child that launches the
2575 * final child. The purpose of the intermediate child
2576 * is to exit, so we can waitpid() it immediately.
2577 * Then the grandchild will not become a zombie.
2579 GPid grandchild_pid;
2581 grandchild_pid = fork ();
2583 if (grandchild_pid < 0)
2585 /* report -1 as child PID */
2586 write_all (child_pid_report_pipe[1], &grandchild_pid,
2587 sizeof(grandchild_pid));
2589 write_err_and_exit (child_err_report_pipe[1],
2592 else if (grandchild_pid == 0)
2594 close_and_invalidate (&child_pid_report_pipe[1]);
2595 do_exec (child_err_report_pipe[1],
2610 search_path_buffer_len,
2613 child_inherits_stdin,
2620 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
2621 close_and_invalidate (&child_pid_report_pipe[1]);
2628 /* Just run the child.
2631 do_exec (child_err_report_pipe[1],
2646 search_path_buffer_len,
2649 child_inherits_stdin,
2662 /* Close the uncared-about ends of the pipes */
2663 close_and_invalidate (&child_err_report_pipe[1]);
2664 close_and_invalidate (&child_pid_report_pipe[1]);
2666 /* If we had an intermediate child, reap it */
2667 if (intermediate_child)
2670 if (waitpid (pid, &status, 0) < 0)
2674 else if (errno == ECHILD)
2675 ; /* do nothing, child already reaped */
2677 g_warning ("waitpid() should not fail in 'fork_exec'");
2682 if (!read_ints (child_err_report_pipe[0],
2685 goto cleanup_and_fail;
2689 /* Error from the child. */
2693 case CHILD_CHDIR_FAILED:
2696 G_SPAWN_ERROR_CHDIR,
2697 _("Failed to change to directory ā%sā (%s)"),
2699 g_strerror (buf[1]));
2703 case CHILD_EXEC_FAILED:
2706 _g_spawn_exec_err_to_g_error (buf[1]),
2707 _("Failed to execute child process ā%sā (%s)"),
2709 g_strerror (buf[1]));
2713 case CHILD_OPEN_FAILED:
2716 G_SPAWN_ERROR_FAILED,
2717 _("Failed to open file to remap file descriptor (%s)"),
2718 g_strerror (buf[1]));
2721 case CHILD_DUPFD_FAILED:
2724 G_SPAWN_ERROR_FAILED,
2725 _("Failed to duplicate file descriptor for child process (%s)"),
2726 g_strerror (buf[1]));
2730 case CHILD_FORK_FAILED:
2734 _("Failed to fork child process (%s)"),
2735 g_strerror (buf[1]));
2738 case CHILD_CLOSE_FAILED:
2741 G_SPAWN_ERROR_FAILED,
2742 _("Failed to close file descriptor for child process (%s)"),
2743 g_strerror (buf[1]));
2749 G_SPAWN_ERROR_FAILED,
2750 _("Unknown error executing child process ā%sā"),
2755 goto cleanup_and_fail;
2758 /* Get child pid from intermediate child pipe. */
2759 if (intermediate_child)
2763 if (!read_ints (child_pid_report_pipe[0],
2764 buf, 1, &n_ints, error))
2765 goto cleanup_and_fail;
2773 G_SPAWN_ERROR_FAILED,
2774 _("Failed to read enough data from child pid pipe (%s)"),
2775 g_strerror (errsv));
2776 goto cleanup_and_fail;
2780 /* we have the child pid */
2785 /* Success against all odds! return the information */
2786 close_and_invalidate (&child_err_report_pipe[0]);
2787 close_and_invalidate (&child_pid_report_pipe[0]);
2789 g_free (search_path_buffer_heap);
2790 g_free (argv_buffer_heap);
2791 g_free (source_fds_copy);
2800 /* Close the uncared-about ends of the pipes */
2801 close_and_invalidate (&stdin_pipe[0]);
2802 close_and_invalidate (&stdout_pipe[1]);
2803 close_and_invalidate (&stderr_pipe[1]);
2805 if (stdin_pipe_out != NULL)
2806 *stdin_pipe_out = g_steal_fd (&stdin_pipe[1]);
2808 if (stdout_pipe_out != NULL)
2809 *stdout_pipe_out = g_steal_fd (&stdout_pipe[0]);
2811 if (stderr_pipe_out != NULL)
2812 *stderr_pipe_out = g_steal_fd (&stderr_pipe[0]);
2818 /* There was an error from the Child, reap the child to avoid it being
2825 if (waitpid (pid, NULL, 0) < 0)
2829 else if (errno == ECHILD)
2830 ; /* do nothing, child already reaped */
2832 g_warning ("waitpid() should not fail in 'fork_exec'");
2836 close_and_invalidate (&stdin_pipe[0]);
2837 close_and_invalidate (&stdin_pipe[1]);
2838 close_and_invalidate (&stdout_pipe[0]);
2839 close_and_invalidate (&stdout_pipe[1]);
2840 close_and_invalidate (&stderr_pipe[0]);
2841 close_and_invalidate (&stderr_pipe[1]);
2843 close_and_invalidate (&child_err_report_pipe[0]);
2844 close_and_invalidate (&child_err_report_pipe[1]);
2845 close_and_invalidate (&child_pid_report_pipe[0]);
2846 close_and_invalidate (&child_pid_report_pipe[1]);
2848 g_clear_pointer (&search_path_buffer_heap, g_free);
2849 g_clear_pointer (&argv_buffer_heap, g_free);
2850 g_clear_pointer (&source_fds_copy, g_free);
2855 /* Based on execvp from GNU C Library */
2857 /* This function is called between fork() and exec() and hence must be
2858 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2860 script_execute (const gchar *file,
2862 gchar **argv_buffer,
2863 gsize argv_buffer_len,
2866 /* Count the arguments. */
2871 /* Construct an argument list for the shell. */
2872 if (argc + 2 > argv_buffer_len)
2875 argv_buffer[0] = (char *) "/bin/sh";
2876 argv_buffer[1] = (char *) file;
2879 argv_buffer[argc + 1] = argv[argc];
2883 /* Execute the shell. */
2885 execve (argv_buffer[0], argv_buffer, envp);
2887 execv (argv_buffer[0], argv_buffer);
2892 /* This function is called between fork() and exec() and hence must be
2893 * async-signal-safe (see signal-safety(7)). */
2895 my_strchrnul (const gchar *str, gchar c)
2897 gchar *p = (gchar*) str;
2898 while (*p && (*p != c))
2904 /* This function is called between fork() and exec() and hence must be
2905 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2907 g_execute (const gchar *file,
2909 gchar **argv_buffer,
2910 gsize argv_buffer_len,
2912 const gchar *search_path,
2913 gchar *search_path_buffer,
2914 gsize search_path_buffer_len)
2916 if (file == NULL || *file == '\0')
2918 /* We check the simple case first. */
2923 if (search_path == NULL || strchr (file, '/') != NULL)
2925 /* Don't search when it contains a slash. */
2927 execve (file, argv, envp);
2931 if (errno == ENOEXEC &&
2932 !script_execute (file, argv, argv_buffer, argv_buffer_len, envp))
2940 gboolean got_eacces = 0;
2941 const gchar *path, *p;
2947 len = strlen (file) + 1;
2948 pathlen = strlen (path);
2949 name = search_path_buffer;
2951 if (search_path_buffer_len < pathlen + len + 1)
2957 /* Copy the file name at the top, including '\0' */
2958 memcpy (name + pathlen + 1, file, len);
2959 name = name + pathlen;
2960 /* And add the slash before the filename */
2969 p = my_strchrnul (path, ':');
2972 /* Two adjacent colons, or a colon at the beginning or the end
2973 * of 'PATH' means to search the current directory.
2977 startp = memcpy (name - (p - path), path, p - path);
2979 /* Try to execute this name. If it works, execv will not return. */
2981 execve (startp, argv, envp);
2983 execv (startp, argv);
2985 if (errno == ENOEXEC &&
2986 !script_execute (startp, argv, argv_buffer, argv_buffer_len, envp))
2995 /* Record the we got a 'Permission denied' error. If we end
2996 * up finding no executable we can use, we want to diagnose
2997 * that we did find one but were denied access.
3009 /* Those errors indicate the file is missing or not executable
3010 * by us, in which case we want to just try the next path
3017 /* Some strange filesystems like AFS return even
3018 * stranger error numbers. They cannot reasonably mean anything
3019 * else so ignore those, too.
3024 /* Some other error means we found an executable file, but
3025 * something went wrong executing it; return the error to our
3031 while (*p++ != '\0');
3033 /* We tried every element and none of them worked. */
3035 /* At least one failure was due to permissions, so report that
3041 /* Return the error from the last attempt (probably ENOENT). */
3046 * g_spawn_close_pid:
3047 * @pid: The process reference to close
3049 * On some platforms, notably Windows, the #GPid type represents a resource
3050 * which must be closed to prevent resource leaking. g_spawn_close_pid()
3051 * is provided for this purpose. It should be used on all platforms, even
3052 * though it doesn't do anything under UNIX.
3055 g_spawn_close_pid (GPid pid)