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 */
38 #endif /* HAVE_SPAWN_H */
40 #ifdef HAVE_CRT_EXTERNS_H
41 #include <crt_externs.h> /* for _NSGetEnviron */
44 #ifdef HAVE_SYS_SELECT_H
45 #include <sys/select.h>
46 #endif /* HAVE_SYS_SELECT_H */
48 #ifdef HAVE_SYS_RESOURCE_H
49 #include <sys/resource.h>
50 #endif /* HAVE_SYS_RESOURCE_H */
52 #if defined(__linux__) || defined(__DragonFly__)
53 #include <sys/syscall.h> /* for syscall and SYS_getdents64 */
57 #include "gspawn-private.h"
59 #include "gtrace-private.h"
60 #include "glib/gstdio.h"
66 #include "gstrfuncs.h"
67 #include "gtestutils.h"
70 #include "glib-unix.h"
72 #define INHERITS_OR_NULL_STDIN (G_SPAWN_STDIN_FROM_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDIN)
73 #define INHERITS_OR_NULL_STDOUT (G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDOUT)
74 #define INHERITS_OR_NULL_STDERR (G_SPAWN_STDERR_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDERR)
76 /* posix_spawn() is assumed the fastest way to spawn, but glibc's
77 * implementation was buggy before glibc 2.24, so avoid it on old versions.
79 #ifdef HAVE_POSIX_SPAWN
82 #if __GLIBC_PREREQ(2,24)
83 #define POSIX_SPAWN_AVAILABLE
86 #else /* !__GLIBC__ */
87 /* Assume that all non-glibc posix_spawn implementations are fine. */
88 #define POSIX_SPAWN_AVAILABLE
89 #endif /* __GLIBC__ */
90 #endif /* HAVE_POSIX_SPAWN */
92 #ifdef HAVE__NSGETENVIRON
93 #define environ (*_NSGetEnviron())
95 extern char **environ;
101 #define HAVE_O_CLOEXEC 1
106 * @Short_description: process launching
107 * @Title: Spawning Processes
109 * GLib supports spawning of processes with an API that is more
110 * convenient than the bare UNIX fork() and exec().
112 * The g_spawn family of functions has synchronous (g_spawn_sync())
113 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
114 * as well as convenience variants that take a complete shell-like
115 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
117 * See #GSubprocess in GIO for a higher-level API that provides
118 * stream interfaces for communication with child processes.
120 * An example of using g_spawn_async_with_pipes():
121 * |[<!-- language="C" -->
122 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
123 * gint child_stdout, child_stderr;
125 * g_autoptr(GError) error = NULL;
127 * // Spawn child process.
128 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
129 * NULL, &child_pid, NULL, &child_stdout,
130 * &child_stderr, &error);
133 * g_error ("Spawning child failed: %s", error->message);
137 * // Add a child watch function which will be called when the child process
139 * g_child_watch_add (child_pid, child_watch_cb, NULL);
141 * // You could watch for output on @child_stdout and @child_stderr using
142 * // #GUnixInputStream or #GIOChannel here.
145 * child_watch_cb (GPid pid,
147 * gpointer user_data)
149 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
150 * g_spawn_check_wait_status (status, NULL) ? "normally" : "abnormally");
152 * // Free any resources associated with the child here, such as I/O channels
153 * // on its stdout and stderr FDs. If you have no code to put in the
154 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
155 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
156 * // otherwise the child process will stay around as a zombie until this
159 * g_spawn_close_pid (pid);
165 static gint g_execute (const gchar *file,
168 gsize argv_buffer_len,
170 const gchar *search_path,
171 gchar *search_path_buffer,
172 gsize search_path_buffer_len);
174 static gboolean fork_exec (gboolean intermediate_child,
175 const gchar *working_directory,
176 const gchar * const *argv,
177 const gchar * const *envp,
178 gboolean close_descriptors,
179 gboolean search_path,
180 gboolean search_path_from_envp,
181 gboolean stdout_to_null,
182 gboolean stderr_to_null,
183 gboolean child_inherits_stdin,
184 gboolean file_and_argv_zero,
185 gboolean cloexec_pipes,
186 GSpawnChildSetupFunc child_setup,
189 gint *stdin_pipe_out,
190 gint *stdout_pipe_out,
191 gint *stderr_pipe_out,
195 const gint *source_fds,
196 const gint *target_fds,
200 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
201 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
205 * @working_directory: (type filename) (nullable): child's current working
206 * directory, or %NULL to inherit parent's
207 * @argv: (array zero-terminated=1) (element-type filename):
208 * child's argument vector
209 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
210 * child's environment, or %NULL to inherit parent's
211 * @flags: flags from #GSpawnFlags
212 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
213 * @user_data: (closure): user data for @child_setup
214 * @child_pid: (out) (optional): return location for child process reference, or %NULL
215 * @error: return location for error
217 * Executes a child program asynchronously.
219 * See g_spawn_async_with_pipes() for a full description; this function
220 * simply calls the g_spawn_async_with_pipes() without any pipes.
222 * You should call g_spawn_close_pid() on the returned child process
223 * reference when you don't need it any more.
225 * If you are writing a GTK application, and the program you are spawning is a
226 * graphical application too, then to ensure that the spawned program opens its
227 * windows on the right screen, you may want to use #GdkAppLaunchContext,
228 * #GAppLaunchContext, or set the %DISPLAY environment variable.
230 * Note that the returned @child_pid on Windows is a handle to the child
231 * process and not its identifier. Process handles and process identifiers
232 * are different concepts on Windows.
234 * Returns: %TRUE on success, %FALSE if error is set
237 g_spawn_async (const gchar *working_directory,
241 GSpawnChildSetupFunc child_setup,
246 return g_spawn_async_with_pipes (working_directory,
256 /* Avoids a danger in threaded situations (calling close()
257 * on a file descriptor twice, and another thread has
258 * re-opened it since the first close)
260 * This function is called between fork() and exec() and hence must be
261 * async-signal-safe (see signal-safety(7)).
264 close_and_invalidate (gint *fd)
273 /* Some versions of OS X define READ_OK in public headers */
278 READ_FAILED = 0, /* FALSE */
284 read_data (GString *str,
292 bytes = read (fd, buf, 4096);
298 g_string_append_len (str, buf, bytes);
301 else if (errno == EINTR)
310 _("Failed to read data from child process (%s)"),
319 * @working_directory: (type filename) (nullable): child's current working
320 * directory, or %NULL to inherit parent's
321 * @argv: (array zero-terminated=1) (element-type filename):
322 * child's argument vector, which must be non-empty and %NULL-terminated
323 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
324 * child's environment, or %NULL to inherit parent's
325 * @flags: flags from #GSpawnFlags
326 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
327 * @user_data: (closure): user data for @child_setup
328 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
329 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
330 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid(), or %NULL
331 * @error: return location for error, or %NULL
333 * Executes a child synchronously (waits for the child to exit before returning).
335 * All output from the child is stored in @standard_output and @standard_error,
336 * if those parameters are non-%NULL. Note that you must set the
337 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
338 * passing %NULL for @standard_output and @standard_error.
340 * If @wait_status is non-%NULL, the platform-specific status of
341 * the child is stored there; see the documentation of
342 * g_spawn_check_wait_status() for how to use and interpret this.
343 * On Unix platforms, note that it is usually not equal
344 * to the integer passed to `exit()` or returned from `main()`.
346 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
347 * @flags, and on POSIX platforms, the same restrictions as for
348 * g_child_watch_source_new() apply.
350 * If an error occurs, no data is returned in @standard_output,
351 * @standard_error, or @wait_status.
353 * This function calls g_spawn_async_with_pipes() internally; see that
354 * function for full details on the other parameters and details on
355 * how these functions work on Windows.
357 * Returns: %TRUE on success, %FALSE if an error was set
360 g_spawn_sync (const gchar *working_directory,
364 GSpawnChildSetupFunc child_setup,
366 gchar **standard_output,
367 gchar **standard_error,
375 GString *outstr = NULL;
376 GString *errstr = NULL;
380 g_return_val_if_fail (argv != NULL, FALSE);
381 g_return_val_if_fail (argv[0] != NULL, FALSE);
382 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
383 g_return_val_if_fail (standard_output == NULL ||
384 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
385 g_return_val_if_fail (standard_error == NULL ||
386 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
388 /* Just to ensure segfaults if callers try to use
389 * these when an error is reported.
392 *standard_output = NULL;
395 *standard_error = NULL;
397 if (!fork_exec (FALSE,
399 (const gchar * const *) argv,
400 (const gchar * const *) envp,
401 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
402 (flags & G_SPAWN_SEARCH_PATH) != 0,
403 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
404 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
405 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
406 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
407 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
408 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
413 standard_output ? &outpipe : NULL,
414 standard_error ? &errpipe : NULL,
420 /* Read data from child. */
426 outstr = g_string_new (NULL);
431 errstr = g_string_new (NULL);
434 /* Read data until we get EOF on both pipes. */
439 /* Any negative FD in the array is ignored, so we can use a fixed length.
440 * We can use UNIX FDs here without worrying about Windows HANDLEs because
441 * the Windows implementation is entirely in gspawn-win32.c. */
444 { outpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
445 { errpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
448 ret = g_poll (fds, G_N_ELEMENTS (fds), -1 /* no timeout */);
462 _("Unexpected error in reading data from a child process (%s)"),
468 if (outpipe >= 0 && fds[0].revents != 0)
470 switch (read_data (outstr, outpipe, error))
476 close_and_invalidate (&outpipe);
487 if (errpipe >= 0 && fds[1].revents != 0)
489 switch (read_data (errstr, errpipe, error))
495 close_and_invalidate (&errpipe);
507 /* These should only be open still if we had an error. */
510 close_and_invalidate (&outpipe);
512 close_and_invalidate (&errpipe);
514 /* Wait for child to exit, even if we have
519 ret = waitpid (pid, &status, 0);
525 else if (errno == ECHILD)
529 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.");
533 /* We don't need the wait status. */
538 if (!failed) /* avoid error pileups */
547 _("Unexpected error in waitpid() (%s)"),
556 g_string_free (outstr, TRUE);
558 g_string_free (errstr, TRUE);
565 *wait_status = status;
568 *standard_output = g_string_free (outstr, FALSE);
571 *standard_error = g_string_free (errstr, FALSE);
578 * g_spawn_async_with_pipes:
579 * @working_directory: (type filename) (nullable): child's current working
580 * directory, or %NULL to inherit parent's, in the GLib file name encoding
581 * @argv: (array zero-terminated=1) (element-type filename): child's argument
582 * vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
583 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
584 * child's environment, or %NULL to inherit parent's, in the GLib file
586 * @flags: flags from #GSpawnFlags
587 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
588 * @user_data: (closure): user data for @child_setup
589 * @child_pid: (out) (optional): return location for child process ID, or %NULL
590 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
591 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
592 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
593 * @error: return location for error
595 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
596 * so no FD assignments are used.
598 * Returns: %TRUE on success, %FALSE if an error was set
601 g_spawn_async_with_pipes (const gchar *working_directory,
605 GSpawnChildSetupFunc child_setup,
608 gint *standard_input,
609 gint *standard_output,
610 gint *standard_error,
613 return g_spawn_async_with_pipes_and_fds (working_directory,
614 (const gchar * const *) argv,
615 (const gchar * const *) envp,
617 child_setup, user_data,
628 * g_spawn_async_with_pipes_and_fds:
629 * @working_directory: (type filename) (nullable): child's current working
630 * directory, or %NULL to inherit parent's, in the GLib file name encoding
631 * @argv: (array zero-terminated=1) (element-type filename): child's argument
632 * vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
633 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
634 * child's environment, or %NULL to inherit parent's, in the GLib file
636 * @flags: flags from #GSpawnFlags
637 * @child_setup: (scope async) (nullable): function to run in the child just before `exec()`
638 * @user_data: (closure): user data for @child_setup
639 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
640 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
641 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
642 * @source_fds: (array length=n_fds) (nullable): array of FDs from the parent
643 * process to make available in the child process
644 * @target_fds: (array length=n_fds) (nullable): array of FDs to remap
645 * @source_fds to in the child process
646 * @n_fds: number of FDs in @source_fds and @target_fds
647 * @child_pid_out: (out) (optional): return location for child process ID, or %NULL
648 * @stdin_pipe_out: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
649 * @stdout_pipe_out: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
650 * @stderr_pipe_out: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
651 * @error: return location for error
653 * Executes a child program asynchronously (your program will not
654 * block waiting for the child to exit).
656 * The child program is specified by the only argument that must be
657 * provided, @argv. @argv should be a %NULL-terminated array of strings,
658 * to be passed as the argument vector for the child. The first string
659 * in @argv is of course the name of the program to execute. By default,
660 * the name of the program must be a full path. If @flags contains the
661 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is used to
662 * search for the executable. If @flags contains the
663 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from @envp
664 * is used to search for the executable. If both the
665 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags are
666 * set, the `PATH` variable from @envp takes precedence over the
667 * environment variable.
669 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag
670 * is not used, then the program will be run from the current directory
671 * (or @working_directory, if specified); this might be unexpected or even
672 * dangerous in some cases when the current directory is world-writable.
674 * On Windows, note that all the string or string vector arguments to
675 * this function and the other `g_spawn*()` functions are in UTF-8, the
676 * GLib file name encoding. Unicode characters that are not part of
677 * the system codepage passed in these arguments will be correctly
678 * available in the spawned program only if it uses wide character API
679 * to retrieve its command line. For C programs built with Microsoft's
680 * tools it is enough to make the program have a `wmain()` instead of
681 * `main()`. `wmain()` has a wide character argument vector as parameter.
683 * At least currently, mingw doesn't support `wmain()`, so if you use
684 * mingw to develop the spawned program, it should call
685 * g_win32_get_command_line() to get arguments in UTF-8.
687 * On Windows the low-level child process creation API `CreateProcess()`
688 * doesn't use argument vectors, but a command line. The C runtime
689 * library's `spawn*()` family of functions (which g_spawn_async_with_pipes()
690 * eventually calls) paste the argument vector elements together into
691 * a command line, and the C runtime startup code does a corresponding
692 * reconstruction of an argument vector from the command line, to be
693 * passed to `main()`. Complications arise when you have argument vector
694 * elements that contain spaces or double quotes. The `spawn*()` functions
695 * don't do any quoting or escaping, but on the other hand the startup
696 * code does do unquoting and unescaping in order to enable receiving
697 * arguments with embedded spaces or double quotes. To work around this
698 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
699 * argument vector elements that need it before calling the C runtime
700 * `spawn()` function.
702 * The returned @child_pid on Windows is a handle to the child
703 * process, not its identifier. Process handles and process
704 * identifiers are different concepts on Windows.
706 * @envp is a %NULL-terminated array of strings, where each string
707 * has the form `KEY=VALUE`. This will become the child's environment.
708 * If @envp is %NULL, the child inherits its parent's environment.
710 * @flags should be the bitwise OR of any flags you want to affect the
711 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
712 * child will not automatically be reaped; you must use a child watch
713 * (g_child_watch_add()) to be notified about the death of the child process,
714 * otherwise it will stay around as a zombie process until this process exits.
715 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
716 * free resources which may be associated with the child process. (On Unix,
717 * using a child watch is equivalent to calling waitpid() or handling
718 * the `SIGCHLD` signal manually. On Windows, calling g_spawn_close_pid()
719 * is equivalent to calling `CloseHandle()` on the process handle returned
720 * in @child_pid). See g_child_watch_add().
722 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
723 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
724 * other open file descriptors will be inherited by the child; otherwise all
725 * descriptors except stdin/stdout/stderr will be closed before calling `exec()`
726 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
727 * absolute path, it will be looked for in the `PATH` environment
728 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
729 * absolute path, it will be looked for in the `PATH` variable from
730 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
731 * are used, the value from @envp takes precedence over the environment.
733 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
734 * standard input (by default, the child's standard input is attached to
735 * `/dev/null`). %G_SPAWN_STDIN_FROM_DEV_NULL explicitly imposes the default
736 * behavior. Both flags cannot be enabled at the same time and, in both cases,
737 * the @stdin_pipe_out argument is ignored.
739 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
740 * will be discarded (by default, it goes to the same location as the parent's
741 * standard output). %G_SPAWN_CHILD_INHERITS_STDOUT explicitly imposes the
742 * default behavior. Both flags cannot be enabled at the same time and, in
743 * both cases, the @stdout_pipe_out argument is ignored.
745 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
746 * will be discarded (by default, it goes to the same location as the parent's
747 * standard error). %G_SPAWN_CHILD_INHERITS_STDERR explicitly imposes the
748 * default behavior. Both flags cannot be enabled at the same time and, in
749 * both cases, the @stderr_pipe_out argument is ignored.
751 * It is valid to pass the same FD in multiple parameters (e.g. you can pass
752 * a single FD for both @stdout_fd and @stderr_fd, and include it in
755 * @source_fds and @target_fds allow zero or more FDs from this process to be
756 * remapped to different FDs in the spawned process. If @n_fds is greater than
757 * zero, @source_fds and @target_fds must both be non-%NULL and the same length.
758 * Each FD in @source_fds is remapped to the FD number at the same index in
759 * @target_fds. The source and target FD may be equal to simply propagate an FD
760 * to the spawned process. FD remappings are processed after standard FDs, so
761 * any target FDs which equal @stdin_fd, @stdout_fd or @stderr_fd will overwrite
762 * them in the spawned process.
764 * @source_fds is supported on Windows since 2.72.
766 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
767 * the file to execute, while the remaining elements are the actual
768 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
769 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
771 * @child_setup and @user_data are a function and user data. On POSIX
772 * platforms, the function is called in the child after GLib has
773 * performed all the setup it plans to perform (including creating
774 * pipes, closing file descriptors, etc.) but before calling `exec()`.
775 * That is, @child_setup is called just before calling `exec()` in the
776 * child. Obviously actions taken in this function will only affect
777 * the child, not the parent.
779 * On Windows, there is no separate `fork()` and `exec()` functionality.
780 * Child processes are created and run with a single API call,
781 * `CreateProcess()`. There is no sensible thing @child_setup
782 * could be used for on Windows so it is ignored and not called.
784 * If non-%NULL, @child_pid will on Unix be filled with the child's
785 * process ID. You can use the process ID to send signals to the child,
786 * or to use g_child_watch_add() (or `waitpid()`) if you specified the
787 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
788 * filled with a handle to the child process only if you specified the
789 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
790 * process using the Win32 API, for example wait for its termination
791 * with the `WaitFor*()` functions, or examine its exit code with
792 * `GetExitCodeProcess()`. You should close the handle with `CloseHandle()`
793 * or g_spawn_close_pid() when you no longer need it.
795 * If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out
796 * locations will be filled with file descriptors for writing to the child's
797 * standard input or reading from its standard output or standard error.
798 * The caller of g_spawn_async_with_pipes() must close these file descriptors
799 * when they are no longer in use. If these parameters are %NULL, the
800 * corresponding pipe won't be created.
802 * If @stdin_pipe_out is %NULL, the child's standard input is attached to
803 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
805 * If @stderr_pipe_out is NULL, the child's standard error goes to the same
806 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
809 * If @stdout_pipe_out is NULL, the child's standard output goes to the same
810 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
813 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
814 * If an error is set, the function returns %FALSE. Errors are reported
815 * even if they occur in the child (for example if the executable in
816 * `@argv[0]` is not found). Typically the `message` field of returned
817 * errors should be displayed to users. Possible errors are those from
818 * the %G_SPAWN_ERROR domain.
820 * If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out,
821 * and @stderr_pipe_out will not be filled with valid values.
823 * If @child_pid is not %NULL and an error does not occur then the returned
824 * process reference must be closed using g_spawn_close_pid().
826 * On modern UNIX platforms, GLib can use an efficient process launching
827 * codepath driven internally by `posix_spawn()`. This has the advantage of
828 * avoiding the fork-time performance costs of cloning the parent process
829 * address space, and avoiding associated memory overcommit checks that are
830 * not relevant in the context of immediately executing a distinct process.
831 * This optimized codepath will be used provided that the following conditions
834 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
835 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
836 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
837 * 4. @working_directory is %NULL
838 * 5. @child_setup is %NULL
839 * 6. The program is of a recognised binary format, or has a shebang.
840 * Otherwise, GLib will have to execute the program through the
841 * shell, which is not done using the optimized codepath.
843 * If you are writing a GTK application, and the program you are spawning is a
844 * graphical application too, then to ensure that the spawned program opens its
845 * windows on the right screen, you may want to use #GdkAppLaunchContext,
846 * #GAppLaunchContext, or set the `DISPLAY` environment variable.
848 * Returns: %TRUE on success, %FALSE if an error was set
853 g_spawn_async_with_pipes_and_fds (const gchar *working_directory,
854 const gchar * const *argv,
855 const gchar * const *envp,
857 GSpawnChildSetupFunc child_setup,
862 const gint *source_fds,
863 const gint *target_fds,
866 gint *stdin_pipe_out,
867 gint *stdout_pipe_out,
868 gint *stderr_pipe_out,
871 g_return_val_if_fail (argv != NULL, FALSE);
872 g_return_val_if_fail (argv[0] != NULL, FALSE);
873 /* can’t both inherit and set pipes to /dev/null */
874 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDIN) != INHERITS_OR_NULL_STDIN, FALSE);
875 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDOUT) != INHERITS_OR_NULL_STDOUT, FALSE);
876 g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDERR) != INHERITS_OR_NULL_STDERR, FALSE);
877 /* can’t use pipes and stdin/stdout/stderr FDs */
878 g_return_val_if_fail (stdin_pipe_out == NULL || stdin_fd < 0, FALSE);
879 g_return_val_if_fail (stdout_pipe_out == NULL || stdout_fd < 0, FALSE);
880 g_return_val_if_fail (stderr_pipe_out == NULL || stderr_fd < 0, FALSE);
882 if ((flags & INHERITS_OR_NULL_STDIN) != 0)
883 stdin_pipe_out = NULL;
884 if ((flags & INHERITS_OR_NULL_STDOUT) != 0)
885 stdout_pipe_out = NULL;
886 if ((flags & INHERITS_OR_NULL_STDERR) != 0)
887 stderr_pipe_out = NULL;
889 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
891 (const gchar * const *) argv,
892 (const gchar * const *) envp,
893 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
894 (flags & G_SPAWN_SEARCH_PATH) != 0,
895 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
896 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
897 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
898 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
899 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
900 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
917 * g_spawn_async_with_fds:
918 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
919 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding;
920 * it must be non-empty and %NULL-terminated
921 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
922 * @flags: flags from #GSpawnFlags
923 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
924 * @user_data: (closure): user data for @child_setup
925 * @child_pid: (out) (optional): return location for child process ID, or %NULL
926 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
927 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
928 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
929 * @error: return location for error
931 * Executes a child program asynchronously.
933 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
934 * so no FD assignments are used.
936 * Returns: %TRUE on success, %FALSE if an error was set
941 g_spawn_async_with_fds (const gchar *working_directory,
945 GSpawnChildSetupFunc child_setup,
953 g_return_val_if_fail (argv != NULL, FALSE);
954 g_return_val_if_fail (argv[0] != NULL, FALSE);
955 g_return_val_if_fail (stdout_fd < 0 ||
956 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
957 g_return_val_if_fail (stderr_fd < 0 ||
958 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
959 /* can't inherit stdin if we have an input pipe. */
960 g_return_val_if_fail (stdin_fd < 0 ||
961 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
963 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
965 (const gchar * const *) argv,
966 (const gchar * const *) envp,
967 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
968 (flags & G_SPAWN_SEARCH_PATH) != 0,
969 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
970 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
971 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
972 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
973 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
974 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
987 * g_spawn_command_line_sync:
988 * @command_line: (type filename): a command line
989 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
990 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
991 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid()
992 * @error: return location for errors
994 * A simple version of g_spawn_sync() with little-used parameters
995 * removed, taking a command line instead of an argument vector.
997 * See g_spawn_sync() for full details.
999 * The @command_line argument will be parsed by g_shell_parse_argv().
1001 * Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag is enabled.
1002 * Note that %G_SPAWN_SEARCH_PATH can have security implications, so
1003 * consider using g_spawn_sync() directly if appropriate.
1005 * Possible errors are those from g_spawn_sync() and those
1006 * from g_shell_parse_argv().
1008 * If @wait_status is non-%NULL, the platform-specific status of
1009 * the child is stored there; see the documentation of
1010 * g_spawn_check_wait_status() for how to use and interpret this.
1011 * On Unix platforms, note that it is usually not equal
1012 * to the integer passed to `exit()` or returned from `main()`.
1014 * On Windows, please note the implications of g_shell_parse_argv()
1015 * parsing @command_line. Parsing is done according to Unix shell rules, not
1016 * Windows command interpreter rules.
1017 * Space is a separator, and backslashes are
1018 * special. Thus you cannot simply pass a @command_line containing
1019 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
1020 * the backslashes will be eaten, and the space will act as a
1021 * separator. You need to enclose such paths with single quotes, like
1022 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
1024 * Returns: %TRUE on success, %FALSE if an error was set
1027 g_spawn_command_line_sync (const gchar *command_line,
1028 gchar **standard_output,
1029 gchar **standard_error,
1034 gchar **argv = NULL;
1036 g_return_val_if_fail (command_line != NULL, FALSE);
1038 /* This will return a runtime error if @command_line is the empty string. */
1039 if (!g_shell_parse_argv (command_line,
1044 retval = g_spawn_sync (NULL,
1047 G_SPAWN_SEARCH_PATH,
1060 * g_spawn_command_line_async:
1061 * @command_line: (type filename): a command line
1062 * @error: return location for errors
1064 * A simple version of g_spawn_async() that parses a command line with
1065 * g_shell_parse_argv() and passes it to g_spawn_async().
1067 * Runs a command line in the background. Unlike g_spawn_async(), the
1068 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
1069 * that %G_SPAWN_SEARCH_PATH can have security implications, so
1070 * consider using g_spawn_async() directly if appropriate. Possible
1071 * errors are those from g_shell_parse_argv() and g_spawn_async().
1073 * The same concerns on Windows apply as for g_spawn_command_line_sync().
1075 * Returns: %TRUE on success, %FALSE if error is set
1078 g_spawn_command_line_async (const gchar *command_line,
1082 gchar **argv = NULL;
1084 g_return_val_if_fail (command_line != NULL, FALSE);
1086 /* This will return a runtime error if @command_line is the empty string. */
1087 if (!g_shell_parse_argv (command_line,
1092 retval = g_spawn_async (NULL,
1095 G_SPAWN_SEARCH_PATH,
1106 * g_spawn_check_wait_status:
1107 * @wait_status: A platform-specific wait status as returned from g_spawn_sync()
1110 * Set @error if @wait_status indicates the child exited abnormally
1111 * (e.g. with a nonzero exit code, or via a fatal signal).
1113 * The g_spawn_sync() and g_child_watch_add() family of APIs return the
1114 * status of subprocesses encoded in a platform-specific way.
1115 * On Unix, this is guaranteed to be in the same format waitpid() returns,
1116 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
1118 * Prior to the introduction of this function in GLib 2.34, interpreting
1119 * @wait_status required use of platform-specific APIs, which is problematic
1120 * for software using GLib as a cross-platform layer.
1122 * Additionally, many programs simply want to determine whether or not
1123 * the child exited successfully, and either propagate a #GError or
1124 * print a message to standard error. In that common case, this function
1125 * can be used. Note that the error message in @error will contain
1126 * human-readable information about the wait status.
1128 * The @domain and @code of @error have special semantics in the case
1129 * where the process has an "exit code", as opposed to being killed by
1130 * a signal. On Unix, this happens if WIFEXITED() would be true of
1131 * @wait_status. On Windows, it is always the case.
1133 * The special semantics are that the actual exit code will be the
1134 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1135 * This allows you to differentiate between different exit codes.
1137 * If the process was terminated by some means other than an exit
1138 * status (for example if it was killed by a signal), the domain will be
1139 * %G_SPAWN_ERROR and the code will be %G_SPAWN_ERROR_FAILED.
1141 * This function just offers convenience; you can of course also check
1142 * the available platform via a macro such as %G_OS_UNIX, and use
1143 * WIFEXITED() and WEXITSTATUS() on @wait_status directly. Do not attempt
1144 * to scan or parse the error message string; it may be translated and/or
1145 * change in future versions of GLib.
1147 * Prior to version 2.70, g_spawn_check_exit_status() provides the same
1148 * functionality, although under a misleading name.
1150 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1151 * @error will be set)
1156 g_spawn_check_wait_status (gint wait_status,
1159 gboolean ret = FALSE;
1161 if (WIFEXITED (wait_status))
1163 if (WEXITSTATUS (wait_status) != 0)
1165 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (wait_status),
1166 _("Child process exited with code %ld"),
1167 (long) WEXITSTATUS (wait_status));
1171 else if (WIFSIGNALED (wait_status))
1173 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1174 _("Child process killed by signal %ld"),
1175 (long) WTERMSIG (wait_status));
1178 else if (WIFSTOPPED (wait_status))
1180 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1181 _("Child process stopped by signal %ld"),
1182 (long) WSTOPSIG (wait_status));
1187 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1188 _("Child process exited abnormally"));
1198 * g_spawn_check_exit_status:
1199 * @wait_status: A status as returned from g_spawn_sync()
1202 * An old name for g_spawn_check_wait_status(), deprecated because its
1203 * name is misleading.
1205 * Despite the name of the function, @wait_status must be the wait status
1206 * as returned by g_spawn_sync(), g_subprocess_get_status(), `waitpid()`,
1207 * etc. On Unix platforms, it is incorrect for it to be the exit status
1208 * as passed to `exit()` or returned by g_subprocess_get_exit_status() or
1211 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1212 * @error will be set)
1216 * Deprecated: 2.70: Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.
1219 g_spawn_check_exit_status (gint wait_status,
1222 return g_spawn_check_wait_status (wait_status, error);
1225 /* This function is called between fork() and exec() and hence must be
1226 * async-signal-safe (see signal-safety(7)). */
1228 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1230 gchar *buf = (gchar *) vbuf;
1232 while (to_write > 0)
1234 gssize count = write (fd, buf, to_write);
1250 /* This function is called between fork() and exec() and hence must be
1251 * async-signal-safe (see signal-safety(7)). */
1254 write_err_and_exit (gint fd, gint msg)
1258 write_all (fd, &msg, sizeof(msg));
1259 write_all (fd, &en, sizeof(en));
1264 /* This function is called between fork() and exec() and hence must be
1265 * async-signal-safe (see signal-safety(7)). */
1267 set_cloexec (void *data, gint fd)
1269 if (fd >= GPOINTER_TO_INT (data))
1270 fcntl (fd, F_SETFD, FD_CLOEXEC);
1275 /* This function is called between fork() and exec() and hence must be
1276 * async-signal-safe (see signal-safety(7)). */
1278 unset_cloexec (int fd)
1283 flags = fcntl (fd, F_GETFD, 0);
1288 flags &= (~FD_CLOEXEC);
1291 result = fcntl (fd, F_SETFD, flags);
1294 while (result == -1 && errsv == EINTR);
1298 /* This function is called between fork() and exec() and hence must be
1299 * async-signal-safe (see signal-safety(7)). */
1301 dupfd_cloexec (int old_fd, int new_fd_min)
1304 #ifdef F_DUPFD_CLOEXEC
1307 fd = fcntl (old_fd, F_DUPFD_CLOEXEC, new_fd_min);
1310 while (fd == -1 && errsv == EINTR);
1312 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
1313 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
1318 fd = fcntl (old_fd, F_DUPFD, new_fd_min);
1321 while (fd == -1 && errsv == EINTR);
1322 flags = fcntl (fd, F_GETFD, 0);
1325 flags |= FD_CLOEXEC;
1328 result = fcntl (fd, F_SETFD, flags);
1331 while (result == -1 && errsv == EINTR);
1337 /* This function is called between fork() and exec() and hence must be
1338 * async-signal-safe (see signal-safety(7)). */
1339 G_GNUC_UNUSED static int
1340 close_func (void *data, int fd)
1342 if (fd >= GPOINTER_TO_INT (data))
1349 struct linux_dirent64
1351 guint64 d_ino; /* 64-bit inode number */
1352 guint64 d_off; /* 64-bit offset to next structure */
1353 unsigned short d_reclen; /* Size of this dirent */
1354 unsigned char d_type; /* File type */
1355 char d_name[]; /* Filename (null-terminated) */
1358 /* This function is called between fork() and exec() and hence must be
1359 * async-signal-safe (see signal-safety(7)). */
1361 filename_to_fd (const char *p)
1365 const int cutoff = G_MAXINT / 10;
1366 const int cutlim = G_MAXINT % 10;
1371 while ((c = *p++) != '\0')
1373 if (c < '0' || c > '9')
1377 /* Check for overflow. */
1378 if (fd > cutoff || (fd == cutoff && c > cutlim))
1388 /* This function is called between fork() and exec() and hence must be
1389 * async-signal-safe (see signal-safety(7)). */
1391 safe_fdwalk (int (*cb)(void *data, int fd), void *data)
1394 /* Use fdwalk function provided by the system if it is known to be
1395 * async-signal safe.
1397 * Currently there are no operating systems known to provide a safe
1398 * implementation, so this section is not used for now.
1400 return fdwalk (cb, data);
1402 /* Fallback implementation of fdwalk. It should be async-signal safe, but it
1403 * may be slow on non-Linux operating systems, especially on systems allowing
1404 * very high number of open file descriptors.
1410 #if 0 && defined(HAVE_SYS_RESOURCE_H)
1415 /* Avoid use of opendir/closedir since these are not async-signal-safe. */
1416 int dir_fd = open ("/proc/self/fd", O_RDONLY | O_DIRECTORY);
1421 struct linux_dirent64 *de;
1423 while ((nread = syscall (SYS_getdents64, dir_fd, buf, sizeof(buf))) > 0)
1425 for (pos = 0; pos < nread; pos += de->d_reclen)
1427 de = (struct linux_dirent64 *)(buf + pos);
1429 fd = filename_to_fd (de->d_name);
1430 if (fd < 0 || fd == dir_fd)
1433 if ((res = cb (data, fd)) != 0)
1438 g_close (dir_fd, NULL);
1442 /* If /proc is not mounted or not accessible we fall back to the old
1447 #if defined(__sun__) && defined(F_PREVFD) && defined(F_NEXTFD)
1449 * Solaris 11.4 has a signal-safe way which allows
1450 * us to find all file descriptors in a process.
1452 * fcntl(fd, F_NEXTFD, maxfd)
1453 * - returns the first allocated file descriptor <= maxfd > fd.
1455 * fcntl(fd, F_PREVFD)
1456 * - return highest allocated file descriptor < fd.
1459 open_max = fcntl (INT_MAX, F_PREVFD); /* find the maximum fd */
1460 if (open_max < 0) /* No open files */
1463 for (fd = -1; (fd = fcntl (fd, F_NEXTFD, open_max)) != -1; )
1464 if ((res = cb (data, fd)) != 0 || fd == open_max)
1468 #if 0 && defined(HAVE_SYS_RESOURCE_H)
1469 /* Use getrlimit() function provided by the system if it is known to be
1470 * async-signal safe.
1472 * Currently there are no operating systems known to provide a safe
1473 * implementation, so this section is not used for now.
1475 if (getrlimit (RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1476 open_max = rl.rlim_max;
1478 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1479 /* Use sysconf() function provided by the system if it is known to be
1480 * async-signal safe.
1482 * FreeBSD: sysconf() is included in the list of async-signal safe functions
1483 * found in https://man.freebsd.org/sigaction(2).
1485 * OpenBSD: sysconf() is included in the list of async-signal safe functions
1486 * found in https://man.openbsd.org/sigaction.2.
1488 * Apple: sysconf() is included in the list of async-signal safe functions
1489 * found in https://opensource.apple.com/source/xnu/xnu-517.12.7/bsd/man/man2/sigaction.2
1492 open_max = sysconf (_SC_OPEN_MAX);
1494 /* Hardcoded fallback: the default process hard limit in Linux as of 2020 */
1498 for (fd = 0; fd < open_max; fd++)
1499 if ((res = cb (data, fd)) != 0)
1507 /* This function is called between fork() and exec() and hence must be
1508 * async-signal-safe (see signal-safety(7)). */
1510 safe_fdwalk_set_cloexec (int lowfd)
1512 #if defined(HAVE_CLOSE_RANGE) && defined(CLOSE_RANGE_CLOEXEC)
1513 /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1514 * around the same time. It was designed for use in async-signal-safe
1515 * situations: https://bugs.python.org/issue38061
1517 * The `CLOSE_RANGE_CLOEXEC` flag was added in Linux 5.11, and is not yet
1518 * present in FreeBSD.
1520 * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
1521 * fall back to safe_fdwalk(). Handle EINVAL in case `CLOSE_RANGE_CLOEXEC`
1522 * is not supported. */
1523 int ret = close_range (lowfd, G_MAXUINT, CLOSE_RANGE_CLOEXEC);
1524 if (ret == 0 || !(errno == ENOSYS || errno == EINVAL))
1526 #endif /* HAVE_CLOSE_RANGE */
1527 return safe_fdwalk (set_cloexec, GINT_TO_POINTER (lowfd));
1530 /* This function is called between fork() and exec() and hence must be
1531 * async-signal-safe (see signal-safety(7)).
1533 * On failure, `-1` will be returned and errno will be set. */
1535 safe_closefrom (int lowfd)
1537 #if defined(__FreeBSD__) || defined(__OpenBSD__) || \
1538 (defined(__sun__) && defined(F_CLOSEFROM))
1539 /* Use closefrom function provided by the system if it is known to be
1540 * async-signal safe.
1542 * FreeBSD: closefrom is included in the list of async-signal safe functions
1543 * found in https://man.freebsd.org/sigaction(2).
1545 * OpenBSD: closefrom is not included in the list, but a direct system call
1546 * should be safe to use.
1548 * In Solaris as of 11.3 SRU 31, closefrom() is also a direct system call.
1549 * On such systems, F_CLOSEFROM is defined.
1551 (void) closefrom (lowfd);
1553 #elif defined(__DragonFly__)
1554 /* It is unclear whether closefrom function included in DragonFlyBSD libc_r
1555 * is safe to use because it calls a lot of library functions. It is also
1556 * unclear whether libc_r itself is still being used. Therefore, we do a
1557 * direct system call here ourselves to avoid possible issues.
1559 (void) syscall (SYS_closefrom, lowfd);
1561 #elif defined(F_CLOSEM)
1562 /* NetBSD and AIX have a special fcntl command which does the same thing as
1563 * closefrom. NetBSD also includes closefrom function, which seems to be a
1564 * simple wrapper of the fcntl command.
1566 return fcntl (lowfd, F_CLOSEM);
1569 #if defined(HAVE_CLOSE_RANGE)
1570 /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1571 * around the same time. It was designed for use in async-signal-safe
1572 * situations: https://bugs.python.org/issue38061
1574 * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
1575 * fall back to safe_fdwalk(). */
1576 int ret = close_range (lowfd, G_MAXUINT, 0);
1577 if (ret == 0 || errno != ENOSYS)
1579 #endif /* HAVE_CLOSE_RANGE */
1580 return safe_fdwalk (close_func, GINT_TO_POINTER (lowfd));
1584 /* This function is called between fork() and exec() and hence must be
1585 * async-signal-safe (see signal-safety(7)). */
1587 safe_dup2 (gint fd1, gint fd2)
1592 ret = dup2 (fd1, fd2);
1593 while (ret < 0 && (errno == EINTR || errno == EBUSY));
1598 /* This function is called between fork() and exec() and hence must be
1599 * async-signal-safe (see signal-safety(7)). */
1601 safe_open (const char *path, gint mode)
1606 ret = open (path, mode);
1607 while (ret < 0 && errno == EINTR);
1622 /* This function is called between fork() and exec() and hence must be
1623 * async-signal-safe (see signal-safety(7)) until it calls exec().
1625 * All callers must guarantee that @argv and @argv[0] are non-NULL. */
1627 do_exec (gint child_err_report_fd,
1632 const gint *target_fds,
1634 const gchar *working_directory,
1635 const gchar * const *argv,
1636 gchar **argv_buffer,
1637 gsize argv_buffer_len,
1638 const gchar * const *envp,
1639 gboolean close_descriptors,
1640 const gchar *search_path,
1641 gchar *search_path_buffer,
1642 gsize search_path_buffer_len,
1643 gboolean stdout_to_null,
1644 gboolean stderr_to_null,
1645 gboolean child_inherits_stdin,
1646 gboolean file_and_argv_zero,
1647 GSpawnChildSetupFunc child_setup,
1651 gint max_target_fd = 0;
1653 if (working_directory && chdir (working_directory) < 0)
1654 write_err_and_exit (child_err_report_fd,
1655 CHILD_CHDIR_FAILED);
1657 /* Redirect pipes as required */
1660 if (safe_dup2 (stdin_fd, 0) < 0)
1661 write_err_and_exit (child_err_report_fd,
1664 if (!((stdout_fd >= 0 || stdout_to_null) && stdin_fd == 1) &&
1665 !((stderr_fd >= 0 || stderr_to_null) && stdin_fd == 2))
1666 set_cloexec (GINT_TO_POINTER(0), stdin_fd);
1668 else if (!child_inherits_stdin)
1670 /* Keep process from blocking on a read of stdin */
1671 gint read_null = safe_open ("/dev/null", O_RDONLY);
1673 write_err_and_exit (child_err_report_fd,
1675 if (safe_dup2 (read_null, 0) < 0)
1676 write_err_and_exit (child_err_report_fd,
1678 close_and_invalidate (&read_null);
1683 if (safe_dup2 (stdout_fd, 1) < 0)
1684 write_err_and_exit (child_err_report_fd,
1687 if (!((stdin_fd >= 0 || !child_inherits_stdin) && stdout_fd == 0) &&
1688 !((stderr_fd >= 0 || stderr_to_null) && stdout_fd == 2))
1689 set_cloexec (GINT_TO_POINTER(0), stdout_fd);
1691 else if (stdout_to_null)
1693 gint write_null = safe_open ("/dev/null", O_WRONLY);
1695 write_err_and_exit (child_err_report_fd,
1697 if (safe_dup2 (write_null, 1) < 0)
1698 write_err_and_exit (child_err_report_fd,
1700 close_and_invalidate (&write_null);
1705 if (safe_dup2 (stderr_fd, 2) < 0)
1706 write_err_and_exit (child_err_report_fd,
1709 if (!((stdin_fd >= 0 || !child_inherits_stdin) && stderr_fd == 0) &&
1710 !((stdout_fd >= 0 || stdout_to_null) && stderr_fd == 1))
1711 set_cloexec (GINT_TO_POINTER(0), stderr_fd);
1713 else if (stderr_to_null)
1715 gint write_null = safe_open ("/dev/null", O_WRONLY);
1717 write_err_and_exit (child_err_report_fd,
1719 if (safe_dup2 (write_null, 2) < 0)
1720 write_err_and_exit (child_err_report_fd,
1722 close_and_invalidate (&write_null);
1725 /* Close all file descriptors but stdin, stdout and stderr, and any of source_fds,
1726 * before we exec. Note that this includes
1727 * child_err_report_fd, which keeps the parent from blocking
1728 * forever on the other end of that pipe.
1730 if (close_descriptors)
1732 if (child_setup == NULL && n_fds == 0)
1734 if (safe_dup2 (child_err_report_fd, 3) < 0)
1735 write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1736 set_cloexec (GINT_TO_POINTER (0), 3);
1737 if (safe_closefrom (4) < 0)
1738 write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1739 child_err_report_fd = 3;
1743 if (safe_fdwalk_set_cloexec (3) < 0)
1744 write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1749 /* We need to do child_err_report_fd anyway */
1750 set_cloexec (GINT_TO_POINTER (0), child_err_report_fd);
1754 * Work through the @source_fds and @target_fds mapping.
1756 * Based on code originally derived from
1757 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
1758 * used under the LGPLv2+ with permission from author. (The code has
1759 * since migrated to vte:src/spawn.cc:SpawnContext::exec and is no longer
1760 * terribly similar to what we have here.)
1765 for (i = 0; i < n_fds; i++)
1766 max_target_fd = MAX (max_target_fd, target_fds[i]);
1768 if (max_target_fd == G_MAXINT)
1771 write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1774 /* If we're doing remapping fd assignments, we need to handle
1775 * the case where the user has specified e.g. 5 -> 4, 4 -> 6.
1776 * We do this by duping all source fds, taking care to ensure the new
1777 * fds are larger than any target fd to avoid introducing new conflicts.
1779 for (i = 0; i < n_fds; i++)
1781 if (source_fds[i] != target_fds[i])
1783 source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
1784 if (source_fds[i] < 0)
1785 write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1789 for (i = 0; i < n_fds; i++)
1791 /* For basic fd assignments (where source == target), we can just
1794 if (source_fds[i] == target_fds[i])
1796 unset_cloexec (source_fds[i]);
1800 /* If any of the @target_fds conflict with @child_err_report_fd,
1801 * dup it so it doesn’t get conflated.
1803 if (target_fds[i] == child_err_report_fd)
1805 child_err_report_fd = dupfd_cloexec (child_err_report_fd, max_target_fd + 1);
1806 if (child_err_report_fd < 0)
1807 write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1810 if (safe_dup2 (source_fds[i], target_fds[i]) < 0)
1811 write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1813 close_and_invalidate (&source_fds[i]);
1818 /* Call user function just before we exec */
1821 (* child_setup) (user_data);
1825 (gchar **) (file_and_argv_zero ? argv + 1 : argv),
1826 argv_buffer, argv_buffer_len,
1827 (gchar **) envp, search_path, search_path_buffer, search_path_buffer_len);
1830 write_err_and_exit (child_err_report_fd,
1847 if (bytes >= sizeof(gint)*2)
1848 break; /* give up, who knows what happened, should not be
1854 ((gchar*)buf) + bytes,
1855 sizeof(gint) * n_ints_in_buf - bytes);
1856 if (chunk < 0 && errno == EINTR)
1863 /* Some weird shit happened, bail out */
1866 G_SPAWN_ERROR_FAILED,
1867 _("Failed to read from child pipe (%s)"),
1868 g_strerror (errsv));
1872 else if (chunk == 0)
1874 else /* chunk > 0 */
1878 *n_ints_read = (gint)(bytes / sizeof(gint));
1883 #ifdef POSIX_SPAWN_AVAILABLE
1885 do_posix_spawn (const gchar * const *argv,
1886 const gchar * const *envp,
1887 gboolean search_path,
1888 gboolean stdout_to_null,
1889 gboolean stderr_to_null,
1890 gboolean child_inherits_stdin,
1891 gboolean file_and_argv_zero,
1893 gint *child_close_fds,
1897 const gint *source_fds,
1898 const gint *target_fds,
1902 gint *duped_source_fds = NULL;
1903 gint max_target_fd = 0;
1904 const gchar * const *argv_pass;
1905 posix_spawnattr_t attr;
1906 posix_spawn_file_actions_t file_actions;
1907 gint parent_close_fds[3];
1908 gsize num_parent_close_fds = 0;
1909 GSList *child_close = NULL;
1915 g_assert (argv != NULL && argv[0] != NULL);
1917 if (*argv[0] == '\0')
1919 /* We check the simple case first. */
1923 r = posix_spawnattr_init (&attr);
1927 if (child_close_fds)
1930 while (child_close_fds[++i] != -1)
1931 child_close = g_slist_prepend (child_close,
1932 GINT_TO_POINTER (child_close_fds[i]));
1935 r = posix_spawnattr_setflags (&attr, POSIX_SPAWN_SETSIGDEF);
1937 goto out_free_spawnattr;
1939 /* Reset some signal handlers that we may use */
1940 sigemptyset (&mask);
1941 sigaddset (&mask, SIGCHLD);
1942 sigaddset (&mask, SIGINT);
1943 sigaddset (&mask, SIGTERM);
1944 sigaddset (&mask, SIGHUP);
1946 r = posix_spawnattr_setsigdefault (&attr, &mask);
1948 goto out_free_spawnattr;
1950 r = posix_spawn_file_actions_init (&file_actions);
1952 goto out_free_spawnattr;
1954 /* Redirect pipes as required */
1958 r = posix_spawn_file_actions_adddup2 (&file_actions, stdin_fd, 0);
1962 if (!g_slist_find (child_close, GINT_TO_POINTER (stdin_fd)))
1963 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdin_fd));
1965 else if (!child_inherits_stdin)
1967 /* Keep process from blocking on a read of stdin */
1968 gint read_null = safe_open ("/dev/null", O_RDONLY | O_CLOEXEC);
1969 g_assert (read_null != -1);
1970 parent_close_fds[num_parent_close_fds++] = read_null;
1972 #ifndef HAVE_O_CLOEXEC
1973 fcntl (read_null, F_SETFD, FD_CLOEXEC);
1976 r = posix_spawn_file_actions_adddup2 (&file_actions, read_null, 0);
1983 r = posix_spawn_file_actions_adddup2 (&file_actions, stdout_fd, 1);
1987 if (!g_slist_find (child_close, GINT_TO_POINTER (stdout_fd)))
1988 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdout_fd));
1990 else if (stdout_to_null)
1992 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1993 g_assert (write_null != -1);
1994 parent_close_fds[num_parent_close_fds++] = write_null;
1996 #ifndef HAVE_O_CLOEXEC
1997 fcntl (write_null, F_SETFD, FD_CLOEXEC);
2000 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 1);
2007 r = posix_spawn_file_actions_adddup2 (&file_actions, stderr_fd, 2);
2011 if (!g_slist_find (child_close, GINT_TO_POINTER (stderr_fd)))
2012 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stderr_fd));
2014 else if (stderr_to_null)
2016 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
2017 g_assert (write_null != -1);
2018 parent_close_fds[num_parent_close_fds++] = write_null;
2020 #ifndef HAVE_O_CLOEXEC
2021 fcntl (write_null, F_SETFD, FD_CLOEXEC);
2024 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 2);
2029 /* If source_fds[i] != target_fds[i], we need to handle the case
2030 * where the user has specified, e.g., 5 -> 4, 4 -> 6. We do this
2031 * by duping the source fds, taking care to ensure the new fds are
2032 * larger than any target fd to avoid introducing new conflicts.
2034 * If source_fds[i] == target_fds[i], then we just need to leak
2035 * the fd into the child process, which we *could* do by temporarily
2036 * unsetting CLOEXEC and then setting it again after we spawn if
2037 * it was originally set. POSIX requires that the addup2 action unset
2038 * CLOEXEC if source and target are identical, so you'd think doing it
2039 * manually wouldn't be needed, but unfortunately as of 2021 many
2040 * libcs still don't do so. Example nonconforming libcs:
2041 * Bionic: https://android.googlesource.com/platform/bionic/+/f6e5b582604715729b09db3e36a7aeb8c24b36a4/libc/bionic/spawn.cpp#71
2042 * uclibc-ng: https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/librt/spawn.c?id=7c36bcae09d66bbaa35cbb02253ae0556f42677e#n88
2044 * Anyway, unsetting CLOEXEC ourselves would open a small race window
2045 * where the fd could be inherited into a child process if another
2046 * thread spawns something at the same time, because we have not
2047 * called fork() and are multithreaded here. This race is avoidable by
2048 * using dupfd_cloexec, which we already have to do to handle the
2049 * source_fds[i] != target_fds[i] case. So let's always do it!
2052 for (i = 0; i < n_fds; i++)
2053 max_target_fd = MAX (max_target_fd, target_fds[i]);
2055 if (max_target_fd == G_MAXINT)
2058 duped_source_fds = g_new (gint, n_fds);
2059 for (i = 0; i < n_fds; i++)
2061 duped_source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
2062 if (duped_source_fds[i] < 0)
2066 for (i = 0; i < n_fds; i++)
2068 r = posix_spawn_file_actions_adddup2 (&file_actions, duped_source_fds[i], target_fds[i]);
2073 /* Intentionally close the fds in the child as the last file action,
2074 * having been careful not to add the same fd to this list twice.
2076 * This is important to allow (e.g.) for the same fd to be passed as stdout
2077 * and stderr (we must not close it before we have dupped it in both places,
2078 * and we must not attempt to close it twice).
2080 for (elem = child_close; elem != NULL; elem = elem->next)
2082 r = posix_spawn_file_actions_addclose (&file_actions,
2083 GPOINTER_TO_INT (elem->data));
2088 argv_pass = file_and_argv_zero ? argv + 1 : argv;
2090 envp = (const gchar * const *) environ;
2092 /* Don't search when it contains a slash. */
2093 if (!search_path || strchr (argv[0], '/') != NULL)
2094 r = posix_spawn (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2096 r = posix_spawnp (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2098 if (r == 0 && child_pid != NULL)
2102 for (i = 0; i < num_parent_close_fds; i++)
2103 close_and_invalidate (&parent_close_fds [i]);
2105 if (duped_source_fds != NULL)
2107 for (i = 0; i < n_fds; i++)
2108 close_and_invalidate (&duped_source_fds[i]);
2109 g_free (duped_source_fds);
2112 posix_spawn_file_actions_destroy (&file_actions);
2114 posix_spawnattr_destroy (&attr);
2115 g_slist_free (child_close);
2119 #endif /* POSIX_SPAWN_AVAILABLE */
2122 fork_exec (gboolean intermediate_child,
2123 const gchar *working_directory,
2124 const gchar * const *argv,
2125 const gchar * const *envp,
2126 gboolean close_descriptors,
2127 gboolean search_path,
2128 gboolean search_path_from_envp,
2129 gboolean stdout_to_null,
2130 gboolean stderr_to_null,
2131 gboolean child_inherits_stdin,
2132 gboolean file_and_argv_zero,
2133 gboolean cloexec_pipes,
2134 GSpawnChildSetupFunc child_setup,
2137 gint *stdin_pipe_out,
2138 gint *stdout_pipe_out,
2139 gint *stderr_pipe_out,
2143 const gint *source_fds,
2144 const gint *target_fds,
2149 gint child_err_report_pipe[2] = { -1, -1 };
2150 gint child_pid_report_pipe[2] = { -1, -1 };
2151 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
2153 const gchar *chosen_search_path;
2154 gchar *search_path_buffer = NULL;
2155 gchar *search_path_buffer_heap = NULL;
2156 gsize search_path_buffer_len = 0;
2157 gchar **argv_buffer = NULL;
2158 gchar **argv_buffer_heap = NULL;
2159 gsize argv_buffer_len = 0;
2160 gint stdin_pipe[2] = { -1, -1 };
2161 gint stdout_pipe[2] = { -1, -1 };
2162 gint stderr_pipe[2] = { -1, -1 };
2163 gint child_close_fds[4] = { -1, -1, -1, -1 };
2164 gint n_child_close_fds = 0;
2165 gint *source_fds_copy = NULL;
2167 g_assert (argv != NULL && argv[0] != NULL);
2168 g_assert (stdin_pipe_out == NULL || stdin_fd < 0);
2169 g_assert (stdout_pipe_out == NULL || stdout_fd < 0);
2170 g_assert (stderr_pipe_out == NULL || stderr_fd < 0);
2172 /* If pipes have been requested, open them */
2173 if (stdin_pipe_out != NULL)
2175 if (!g_unix_open_pipe (stdin_pipe, pipe_flags, error))
2176 goto cleanup_and_fail;
2177 child_close_fds[n_child_close_fds++] = stdin_pipe[1];
2178 stdin_fd = stdin_pipe[0];
2181 if (stdout_pipe_out != NULL)
2183 if (!g_unix_open_pipe (stdout_pipe, pipe_flags, error))
2184 goto cleanup_and_fail;
2185 child_close_fds[n_child_close_fds++] = stdout_pipe[0];
2186 stdout_fd = stdout_pipe[1];
2189 if (stderr_pipe_out != NULL)
2191 if (!g_unix_open_pipe (stderr_pipe, pipe_flags, error))
2192 goto cleanup_and_fail;
2193 child_close_fds[n_child_close_fds++] = stderr_pipe[0];
2194 stderr_fd = stderr_pipe[1];
2197 child_close_fds[n_child_close_fds++] = -1;
2199 #ifdef POSIX_SPAWN_AVAILABLE
2200 if (!intermediate_child && working_directory == NULL && !close_descriptors &&
2201 !search_path_from_envp && child_setup == NULL)
2203 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2204 "GLib", "posix_spawn",
2207 status = do_posix_spawn (argv,
2212 child_inherits_stdin,
2225 if (status != ENOEXEC)
2229 G_SPAWN_ERROR_FAILED,
2230 _("Failed to spawn child process “%s” (%s)"),
2232 g_strerror (status));
2233 goto cleanup_and_fail;
2236 /* posix_spawn is not intended to support script execution. It does in
2237 * some situations on some glibc versions, but that will be fixed.
2238 * So if it fails with ENOEXEC, we fall through to the regular
2239 * gspawn codepath so that script execution can be attempted,
2240 * per standard gspawn behaviour. */
2241 g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
2245 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2247 "posix_spawn avoided %s%s%s%s%s",
2248 !intermediate_child ? "" : "(automatic reaping requested) ",
2249 working_directory == NULL ? "" : "(workdir specified) ",
2250 !close_descriptors ? "" : "(fd close requested) ",
2251 !search_path_from_envp ? "" : "(using envp for search path) ",
2252 child_setup == NULL ? "" : "(child_setup specified) ");
2254 #endif /* POSIX_SPAWN_AVAILABLE */
2256 /* Choose a search path. This has to be done before calling fork()
2257 * as getenv() isn’t async-signal-safe (see `man 7 signal-safety`). */
2258 chosen_search_path = NULL;
2259 if (search_path_from_envp)
2260 chosen_search_path = g_environ_getenv ((gchar **) envp, "PATH");
2261 if (search_path && chosen_search_path == NULL)
2262 chosen_search_path = g_getenv ("PATH");
2264 if ((search_path || search_path_from_envp) && chosen_search_path == NULL)
2266 /* There is no 'PATH' in the environment. The default
2267 * * search path in libc is the current directory followed by
2268 * * the path 'confstr' returns for '_CS_PATH'.
2271 /* In GLib we put . last, for security, and don't use the
2272 * * unportable confstr(); UNIX98 does not actually specify
2273 * * what to search if PATH is unset. POSIX may, dunno.
2276 chosen_search_path = "/bin:/usr/bin:.";
2279 if (search_path || search_path_from_envp)
2280 g_assert (chosen_search_path != NULL);
2282 g_assert (chosen_search_path == NULL);
2284 /* Allocate a buffer which the fork()ed child can use to assemble potential
2285 * paths for the binary to exec(), combining the argv[0] and elements from
2286 * the chosen_search_path. This can’t be done in the child because malloc()
2287 * (or alloca()) are not async-signal-safe (see `man 7 signal-safety`).
2289 * Add 2 for the nul terminator and a leading `/`. */
2290 if (chosen_search_path != NULL)
2292 search_path_buffer_len = strlen (chosen_search_path) + strlen (argv[0]) + 2;
2293 if (search_path_buffer_len < 4000)
2295 /* Prefer small stack allocations to avoid valgrind leak warnings
2296 * in forked child. The 4000B cutoff is arbitrary. */
2297 search_path_buffer = g_alloca (search_path_buffer_len);
2301 search_path_buffer_heap = g_malloc (search_path_buffer_len);
2302 search_path_buffer = search_path_buffer_heap;
2306 if (search_path || search_path_from_envp)
2307 g_assert (search_path_buffer != NULL);
2309 g_assert (search_path_buffer == NULL);
2311 /* And allocate a buffer which is 2 elements longer than @argv, so that if
2312 * script_execute() has to be called later on, it can build a wrapper argv
2313 * array in this buffer. */
2314 argv_buffer_len = g_strv_length ((gchar **) argv) + 2;
2315 if (argv_buffer_len < 4000 / sizeof (gchar *))
2317 /* Prefer small stack allocations to avoid valgrind leak warnings
2318 * in forked child. The 4000B cutoff is arbitrary. */
2319 argv_buffer = g_newa (gchar *, argv_buffer_len);
2323 argv_buffer_heap = g_new (gchar *, argv_buffer_len);
2324 argv_buffer = argv_buffer_heap;
2327 /* And one to hold a copy of @source_fds for later manipulation in do_exec(). */
2328 source_fds_copy = g_new (int, n_fds);
2330 memcpy (source_fds_copy, source_fds, sizeof (*source_fds) * n_fds);
2332 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
2333 goto cleanup_and_fail;
2335 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
2336 goto cleanup_and_fail;
2347 _("Failed to fork (%s)"),
2348 g_strerror (errsv));
2350 goto cleanup_and_fail;
2354 /* Immediate child. This may or may not be the child that
2355 * actually execs the new process.
2358 /* Reset some signal handlers that we may use */
2359 signal (SIGCHLD, SIG_DFL);
2360 signal (SIGINT, SIG_DFL);
2361 signal (SIGTERM, SIG_DFL);
2362 signal (SIGHUP, SIG_DFL);
2364 /* Be sure we crash if the parent exits
2365 * and we write to the err_report_pipe
2367 signal (SIGPIPE, SIG_DFL);
2369 /* Close the parent's end of the pipes;
2370 * not needed in the close_descriptors case,
2373 close_and_invalidate (&child_err_report_pipe[0]);
2374 close_and_invalidate (&child_pid_report_pipe[0]);
2375 if (child_close_fds[0] != -1)
2378 while (child_close_fds[++i] != -1)
2379 close_and_invalidate (&child_close_fds[i]);
2382 if (intermediate_child)
2384 /* We need to fork an intermediate child that launches the
2385 * final child. The purpose of the intermediate child
2386 * is to exit, so we can waitpid() it immediately.
2387 * Then the grandchild will not become a zombie.
2389 GPid grandchild_pid;
2391 grandchild_pid = fork ();
2393 if (grandchild_pid < 0)
2395 /* report -1 as child PID */
2396 write_all (child_pid_report_pipe[1], &grandchild_pid,
2397 sizeof(grandchild_pid));
2399 write_err_and_exit (child_err_report_pipe[1],
2402 else if (grandchild_pid == 0)
2404 close_and_invalidate (&child_pid_report_pipe[1]);
2405 do_exec (child_err_report_pipe[1],
2420 search_path_buffer_len,
2423 child_inherits_stdin,
2430 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
2431 close_and_invalidate (&child_pid_report_pipe[1]);
2438 /* Just run the child.
2441 do_exec (child_err_report_pipe[1],
2456 search_path_buffer_len,
2459 child_inherits_stdin,
2472 /* Close the uncared-about ends of the pipes */
2473 close_and_invalidate (&child_err_report_pipe[1]);
2474 close_and_invalidate (&child_pid_report_pipe[1]);
2476 /* If we had an intermediate child, reap it */
2477 if (intermediate_child)
2480 if (waitpid (pid, &status, 0) < 0)
2484 else if (errno == ECHILD)
2485 ; /* do nothing, child already reaped */
2487 g_warning ("waitpid() should not fail in 'fork_exec'");
2492 if (!read_ints (child_err_report_pipe[0],
2495 goto cleanup_and_fail;
2499 /* Error from the child. */
2503 case CHILD_CHDIR_FAILED:
2506 G_SPAWN_ERROR_CHDIR,
2507 _("Failed to change to directory “%s” (%s)"),
2509 g_strerror (buf[1]));
2513 case CHILD_EXEC_FAILED:
2516 _g_spawn_exec_err_to_g_error (buf[1]),
2517 _("Failed to execute child process “%s” (%s)"),
2519 g_strerror (buf[1]));
2523 case CHILD_OPEN_FAILED:
2526 G_SPAWN_ERROR_FAILED,
2527 _("Failed to open file to remap file descriptor (%s)"),
2528 g_strerror (buf[1]));
2531 case CHILD_DUP2_FAILED:
2534 G_SPAWN_ERROR_FAILED,
2535 _("Failed to duplicate file descriptor for child process (%s)"),
2536 g_strerror (buf[1]));
2540 case CHILD_FORK_FAILED:
2544 _("Failed to fork child process (%s)"),
2545 g_strerror (buf[1]));
2548 case CHILD_CLOSE_FAILED:
2551 G_SPAWN_ERROR_FAILED,
2552 _("Failed to close file descriptor for child process (%s)"),
2553 g_strerror (buf[1]));
2559 G_SPAWN_ERROR_FAILED,
2560 _("Unknown error executing child process “%s”"),
2565 goto cleanup_and_fail;
2568 /* Get child pid from intermediate child pipe. */
2569 if (intermediate_child)
2573 if (!read_ints (child_pid_report_pipe[0],
2574 buf, 1, &n_ints, error))
2575 goto cleanup_and_fail;
2583 G_SPAWN_ERROR_FAILED,
2584 _("Failed to read enough data from child pid pipe (%s)"),
2585 g_strerror (errsv));
2586 goto cleanup_and_fail;
2590 /* we have the child pid */
2595 /* Success against all odds! return the information */
2596 close_and_invalidate (&child_err_report_pipe[0]);
2597 close_and_invalidate (&child_pid_report_pipe[0]);
2599 g_free (search_path_buffer_heap);
2600 g_free (argv_buffer_heap);
2601 g_free (source_fds_copy);
2610 /* Close the uncared-about ends of the pipes */
2611 close_and_invalidate (&stdin_pipe[0]);
2612 close_and_invalidate (&stdout_pipe[1]);
2613 close_and_invalidate (&stderr_pipe[1]);
2615 if (stdin_pipe_out != NULL)
2616 *stdin_pipe_out = g_steal_fd (&stdin_pipe[1]);
2618 if (stdout_pipe_out != NULL)
2619 *stdout_pipe_out = g_steal_fd (&stdout_pipe[0]);
2621 if (stderr_pipe_out != NULL)
2622 *stderr_pipe_out = g_steal_fd (&stderr_pipe[0]);
2628 /* There was an error from the Child, reap the child to avoid it being
2635 if (waitpid (pid, NULL, 0) < 0)
2639 else if (errno == ECHILD)
2640 ; /* do nothing, child already reaped */
2642 g_warning ("waitpid() should not fail in 'fork_exec'");
2646 close_and_invalidate (&stdin_pipe[0]);
2647 close_and_invalidate (&stdin_pipe[1]);
2648 close_and_invalidate (&stdout_pipe[0]);
2649 close_and_invalidate (&stdout_pipe[1]);
2650 close_and_invalidate (&stderr_pipe[0]);
2651 close_and_invalidate (&stderr_pipe[1]);
2653 close_and_invalidate (&child_err_report_pipe[0]);
2654 close_and_invalidate (&child_err_report_pipe[1]);
2655 close_and_invalidate (&child_pid_report_pipe[0]);
2656 close_and_invalidate (&child_pid_report_pipe[1]);
2658 g_clear_pointer (&search_path_buffer_heap, g_free);
2659 g_clear_pointer (&argv_buffer_heap, g_free);
2660 g_clear_pointer (&source_fds_copy, g_free);
2665 /* Based on execvp from GNU C Library */
2667 /* This function is called between fork() and exec() and hence must be
2668 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2670 script_execute (const gchar *file,
2672 gchar **argv_buffer,
2673 gsize argv_buffer_len,
2676 /* Count the arguments. */
2681 /* Construct an argument list for the shell. */
2682 if (argc + 2 > argv_buffer_len)
2685 argv_buffer[0] = (char *) "/bin/sh";
2686 argv_buffer[1] = (char *) file;
2689 argv_buffer[argc + 1] = argv[argc];
2693 /* Execute the shell. */
2695 execve (argv_buffer[0], argv_buffer, envp);
2697 execv (argv_buffer[0], argv_buffer);
2702 /* This function is called between fork() and exec() and hence must be
2703 * async-signal-safe (see signal-safety(7)). */
2705 my_strchrnul (const gchar *str, gchar c)
2707 gchar *p = (gchar*) str;
2708 while (*p && (*p != c))
2714 /* This function is called between fork() and exec() and hence must be
2715 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2717 g_execute (const gchar *file,
2719 gchar **argv_buffer,
2720 gsize argv_buffer_len,
2722 const gchar *search_path,
2723 gchar *search_path_buffer,
2724 gsize search_path_buffer_len)
2726 if (file == NULL || *file == '\0')
2728 /* We check the simple case first. */
2733 if (search_path == NULL || strchr (file, '/') != NULL)
2735 /* Don't search when it contains a slash. */
2737 execve (file, argv, envp);
2741 if (errno == ENOEXEC &&
2742 !script_execute (file, argv, argv_buffer, argv_buffer_len, envp))
2750 gboolean got_eacces = 0;
2751 const gchar *path, *p;
2757 len = strlen (file) + 1;
2758 pathlen = strlen (path);
2759 name = search_path_buffer;
2761 if (search_path_buffer_len < pathlen + len + 1)
2767 /* Copy the file name at the top, including '\0' */
2768 memcpy (name + pathlen + 1, file, len);
2769 name = name + pathlen;
2770 /* And add the slash before the filename */
2779 p = my_strchrnul (path, ':');
2782 /* Two adjacent colons, or a colon at the beginning or the end
2783 * of 'PATH' means to search the current directory.
2787 startp = memcpy (name - (p - path), path, p - path);
2789 /* Try to execute this name. If it works, execv will not return. */
2791 execve (startp, argv, envp);
2793 execv (startp, argv);
2795 if (errno == ENOEXEC &&
2796 !script_execute (startp, argv, argv_buffer, argv_buffer_len, envp))
2805 /* Record the we got a 'Permission denied' error. If we end
2806 * up finding no executable we can use, we want to diagnose
2807 * that we did find one but were denied access.
2819 /* Those errors indicate the file is missing or not executable
2820 * by us, in which case we want to just try the next path
2827 /* Some strange filesystems like AFS return even
2828 * stranger error numbers. They cannot reasonably mean anything
2829 * else so ignore those, too.
2834 /* Some other error means we found an executable file, but
2835 * something went wrong executing it; return the error to our
2841 while (*p++ != '\0');
2843 /* We tried every element and none of them worked. */
2845 /* At least one failure was due to permissions, so report that
2851 /* Return the error from the last attempt (probably ENOENT). */
2856 * g_spawn_close_pid:
2857 * @pid: The process reference to close
2859 * On some platforms, notably Windows, the #GPid type represents a resource
2860 * which must be closed to prevent resource leaking. g_spawn_close_pid()
2861 * is provided for this purpose. It should be used on all platforms, even
2862 * though it doesn't do anything under UNIX.
2865 g_spawn_close_pid (GPid pid)