1 /* gspawn.c - Process launching
3 * Copyright 2000 Red Hat, Inc.
4 * g_execvpe implementation based on GNU libc execvp:
5 * Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
24 #include <sys/types.h>
31 #include <stdlib.h> /* for fdwalk */
36 #endif /* HAVE_SPAWN_H */
38 #ifdef HAVE_CRT_EXTERNS_H
39 #include <crt_externs.h> /* for _NSGetEnviron */
42 #ifdef HAVE_SYS_SELECT_H
43 #include <sys/select.h>
44 #endif /* HAVE_SYS_SELECT_H */
46 #ifdef HAVE_SYS_RESOURCE_H
47 #include <sys/resource.h>
48 #endif /* HAVE_SYS_RESOURCE_H */
50 #if defined(__linux__) || defined(__DragonFly__)
51 #include <sys/syscall.h> /* for syscall and SYS_getdents64 */
55 #include "gspawn-private.h"
57 #include "gtrace-private.h"
58 #include "glib/gstdio.h"
64 #include "gstrfuncs.h"
65 #include "gtestutils.h"
68 #include "glib-unix.h"
70 /* posix_spawn() is assumed the fastest way to spawn, but glibc's
71 * implementation was buggy before glibc 2.24, so avoid it on old versions.
73 #ifdef HAVE_POSIX_SPAWN
76 #if __GLIBC_PREREQ(2,24)
77 #define POSIX_SPAWN_AVAILABLE
80 #else /* !__GLIBC__ */
81 /* Assume that all non-glibc posix_spawn implementations are fine. */
82 #define POSIX_SPAWN_AVAILABLE
83 #endif /* __GLIBC__ */
84 #endif /* HAVE_POSIX_SPAWN */
86 #ifdef HAVE__NSGETENVIRON
87 #define environ (*_NSGetEnviron())
89 extern char **environ;
95 #define HAVE_O_CLOEXEC 1
100 * @Short_description: process launching
101 * @Title: Spawning Processes
103 * GLib supports spawning of processes with an API that is more
104 * convenient than the bare UNIX fork() and exec().
106 * The g_spawn family of functions has synchronous (g_spawn_sync())
107 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
108 * as well as convenience variants that take a complete shell-like
109 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
111 * See #GSubprocess in GIO for a higher-level API that provides
112 * stream interfaces for communication with child processes.
114 * An example of using g_spawn_async_with_pipes():
115 * |[<!-- language="C" -->
116 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
117 * gint child_stdout, child_stderr;
119 * g_autoptr(GError) error = NULL;
121 * // Spawn child process.
122 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
123 * NULL, &child_pid, NULL, &child_stdout,
124 * &child_stderr, &error);
127 * g_error ("Spawning child failed: %s", error->message);
131 * // Add a child watch function which will be called when the child process
133 * g_child_watch_add (child_pid, child_watch_cb, NULL);
135 * // You could watch for output on @child_stdout and @child_stderr using
136 * // #GUnixInputStream or #GIOChannel here.
139 * child_watch_cb (GPid pid,
141 * gpointer user_data)
143 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
144 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
146 * // Free any resources associated with the child here, such as I/O channels
147 * // on its stdout and stderr FDs. If you have no code to put in the
148 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
149 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
150 * // otherwise the child process will stay around as a zombie until this
153 * g_spawn_close_pid (pid);
159 static gint safe_close (gint fd);
161 static gint g_execute (const gchar *file,
164 gsize argv_buffer_len,
166 const gchar *search_path,
167 gchar *search_path_buffer,
168 gsize search_path_buffer_len);
170 static gboolean fork_exec (gboolean intermediate_child,
171 const gchar *working_directory,
172 const gchar * const *argv,
173 const gchar * const *envp,
174 gboolean close_descriptors,
175 gboolean search_path,
176 gboolean search_path_from_envp,
177 gboolean stdout_to_null,
178 gboolean stderr_to_null,
179 gboolean child_inherits_stdin,
180 gboolean file_and_argv_zero,
181 gboolean cloexec_pipes,
182 GSpawnChildSetupFunc child_setup,
185 gint *stdin_pipe_out,
186 gint *stdout_pipe_out,
187 gint *stderr_pipe_out,
191 const gint *source_fds,
192 const gint *target_fds,
196 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
197 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
201 * @working_directory: (type filename) (nullable): child's current working
202 * directory, or %NULL to inherit parent's
203 * @argv: (array zero-terminated=1) (element-type filename):
204 * child's argument vector
205 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
206 * child's environment, or %NULL to inherit parent's
207 * @flags: flags from #GSpawnFlags
208 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
209 * @user_data: (closure): user data for @child_setup
210 * @child_pid: (out) (optional): return location for child process reference, or %NULL
211 * @error: return location for error
213 * See g_spawn_async_with_pipes() for a full description; this function
214 * simply calls the g_spawn_async_with_pipes() without any pipes.
216 * You should call g_spawn_close_pid() on the returned child process
217 * reference when you don't need it any more.
219 * If you are writing a GTK+ application, and the program you are spawning is a
220 * graphical application too, then to ensure that the spawned program opens its
221 * windows on the right screen, you may want to use #GdkAppLaunchContext,
222 * #GAppLaunchContext, or set the %DISPLAY environment variable.
224 * Note that the returned @child_pid on Windows is a handle to the child
225 * process and not its identifier. Process handles and process identifiers
226 * are different concepts on Windows.
228 * Returns: %TRUE on success, %FALSE if error is set
231 g_spawn_async (const gchar *working_directory,
235 GSpawnChildSetupFunc child_setup,
240 g_return_val_if_fail (argv != NULL, FALSE);
242 return g_spawn_async_with_pipes (working_directory,
252 /* This function is called between fork() and exec() and hence must be
253 * async-signal-safe (see signal-safety(7)). */
262 /* Avoids a danger in threaded situations (calling close()
263 * on a file descriptor twice, and another thread has
264 * re-opened it since the first close)
266 * This function is called between fork() and exec() and hence must be
267 * async-signal-safe (see signal-safety(7)).
270 close_and_invalidate (gint *fd)
281 /* Some versions of OS X define READ_OK in public headers */
286 READ_FAILED = 0, /* FALSE */
292 read_data (GString *str,
300 bytes = read (fd, buf, 4096);
306 g_string_append_len (str, buf, bytes);
309 else if (errno == EINTR)
318 _("Failed to read data from child process (%s)"),
327 * @working_directory: (type filename) (nullable): child's current working
328 * directory, or %NULL to inherit parent's
329 * @argv: (array zero-terminated=1) (element-type filename):
330 * child's argument vector
331 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
332 * child's environment, or %NULL to inherit parent's
333 * @flags: flags from #GSpawnFlags
334 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
335 * @user_data: (closure): user data for @child_setup
336 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
337 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
338 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
339 * @error: return location for error, or %NULL
341 * Executes a child synchronously (waits for the child to exit before returning).
342 * All output from the child is stored in @standard_output and @standard_error,
343 * if those parameters are non-%NULL. Note that you must set the
344 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
345 * passing %NULL for @standard_output and @standard_error.
347 * If @exit_status is non-%NULL, the platform-specific exit status of
348 * the child is stored there; see the documentation of
349 * g_spawn_check_exit_status() for how to use and interpret this.
350 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
351 * @flags, and on POSIX platforms, the same restrictions as for
352 * g_child_watch_source_new() apply.
354 * If an error occurs, no data is returned in @standard_output,
355 * @standard_error, or @exit_status.
357 * This function calls g_spawn_async_with_pipes() internally; see that
358 * function for full details on the other parameters and details on
359 * how these functions work on Windows.
361 * Returns: %TRUE on success, %FALSE if an error was set
364 g_spawn_sync (const gchar *working_directory,
368 GSpawnChildSetupFunc child_setup,
370 gchar **standard_output,
371 gchar **standard_error,
379 GString *outstr = NULL;
380 GString *errstr = NULL;
384 g_return_val_if_fail (argv != NULL, FALSE);
385 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
386 g_return_val_if_fail (standard_output == NULL ||
387 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
388 g_return_val_if_fail (standard_error == NULL ||
389 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
391 /* Just to ensure segfaults if callers try to use
392 * these when an error is reported.
395 *standard_output = NULL;
398 *standard_error = NULL;
400 if (!fork_exec (FALSE,
402 (const gchar * const *) argv,
403 (const gchar * const *) envp,
404 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
405 (flags & G_SPAWN_SEARCH_PATH) != 0,
406 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
407 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
408 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
409 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
410 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
411 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
416 standard_output ? &outpipe : NULL,
417 standard_error ? &errpipe : NULL,
423 /* Read data from child. */
429 outstr = g_string_new (NULL);
434 errstr = g_string_new (NULL);
437 /* Read data until we get EOF on both pipes. */
442 /* Any negative FD in the array is ignored, so we can use a fixed length.
443 * We can use UNIX FDs here without worrying about Windows HANDLEs because
444 * the Windows implementation is entirely in gspawn-win32.c. */
447 { outpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
448 { errpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
451 ret = g_poll (fds, G_N_ELEMENTS (fds), -1 /* no timeout */);
465 _("Unexpected error in reading data from a child process (%s)"),
471 if (outpipe >= 0 && fds[0].revents != 0)
473 switch (read_data (outstr, outpipe, error))
479 close_and_invalidate (&outpipe);
490 if (errpipe >= 0 && fds[1].revents != 0)
492 switch (read_data (errstr, errpipe, error))
498 close_and_invalidate (&errpipe);
510 /* These should only be open still if we had an error. */
513 close_and_invalidate (&outpipe);
515 close_and_invalidate (&errpipe);
517 /* Wait for child to exit, even if we have
522 ret = waitpid (pid, &status, 0);
528 else if (errno == ECHILD)
532 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
536 /* We don't need the exit status. */
541 if (!failed) /* avoid error pileups */
550 _("Unexpected error in waitpid() (%s)"),
559 g_string_free (outstr, TRUE);
561 g_string_free (errstr, TRUE);
568 *exit_status = status;
571 *standard_output = g_string_free (outstr, FALSE);
574 *standard_error = g_string_free (errstr, FALSE);
581 * g_spawn_async_with_pipes:
582 * @working_directory: (type filename) (nullable): child's current working
583 * directory, or %NULL to inherit parent's, in the GLib file name encoding
584 * @argv: (array zero-terminated=1) (element-type filename): child's argument
585 * vector, in the GLib file name encoding
586 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
587 * child's environment, or %NULL to inherit parent's, in the GLib file
589 * @flags: flags from #GSpawnFlags
590 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
591 * @user_data: (closure): user data for @child_setup
592 * @child_pid: (out) (optional): return location for child process ID, or %NULL
593 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
594 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
595 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
596 * @error: return location for error
598 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
599 * so no FD assignments are used.
601 * Returns: %TRUE on success, %FALSE if an error was set
604 g_spawn_async_with_pipes (const gchar *working_directory,
608 GSpawnChildSetupFunc child_setup,
611 gint *standard_input,
612 gint *standard_output,
613 gint *standard_error,
616 g_return_val_if_fail (argv != NULL, FALSE);
617 g_return_val_if_fail (standard_output == NULL ||
618 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
619 g_return_val_if_fail (standard_error == NULL ||
620 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
621 /* can't inherit stdin if we have an input pipe. */
622 g_return_val_if_fail (standard_input == NULL ||
623 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
625 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
627 (const gchar * const *) argv,
628 (const gchar * const *) envp,
629 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
630 (flags & G_SPAWN_SEARCH_PATH) != 0,
631 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
632 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
633 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
634 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
635 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
636 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
649 * g_spawn_async_with_pipes_and_fds:
650 * @working_directory: (type filename) (nullable): child's current working
651 * directory, or %NULL to inherit parent's, in the GLib file name encoding
652 * @argv: (array zero-terminated=1) (element-type filename): child's argument
653 * vector, in the GLib file name encoding
654 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
655 * child's environment, or %NULL to inherit parent's, in the GLib file
657 * @flags: flags from #GSpawnFlags
658 * @child_setup: (scope async) (nullable): function to run in the child just before `exec()`
659 * @user_data: (closure): user data for @child_setup
660 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
661 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
662 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
663 * @source_fds: (array length=n_fds) (nullable): array of FDs from the parent
664 * process to make available in the child process
665 * @target_fds: (array length=n_fds) (nullable): array of FDs to remap
666 * @source_fds to in the child process
667 * @n_fds: number of FDs in @source_fds and @target_fds
668 * @child_pid_out: (out) (optional): return location for child process ID, or %NULL
669 * @stdin_pipe_out: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
670 * @stdout_pipe_out: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
671 * @stderr_pipe_out: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
672 * @error: return location for error
674 * Executes a child program asynchronously (your program will not
675 * block waiting for the child to exit). The child program is
676 * specified by the only argument that must be provided, @argv.
677 * @argv should be a %NULL-terminated array of strings, to be passed
678 * as the argument vector for the child. The first string in @argv
679 * is of course the name of the program to execute. By default, the
680 * name of the program must be a full path. If @flags contains the
681 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
682 * used to search for the executable. If @flags contains the
683 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
684 * @envp is used to search for the executable. If both the
685 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
686 * are set, the `PATH` variable from @envp takes precedence over
687 * the environment variable.
689 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
690 * used, then the program will be run from the current directory (or
691 * @working_directory, if specified); this might be unexpected or even
692 * dangerous in some cases when the current directory is world-writable.
694 * On Windows, note that all the string or string vector arguments to
695 * this function and the other g_spawn*() functions are in UTF-8, the
696 * GLib file name encoding. Unicode characters that are not part of
697 * the system codepage passed in these arguments will be correctly
698 * available in the spawned program only if it uses wide character API
699 * to retrieve its command line. For C programs built with Microsoft's
700 * tools it is enough to make the program have a wmain() instead of
701 * main(). wmain() has a wide character argument vector as parameter.
703 * At least currently, mingw doesn't support wmain(), so if you use
704 * mingw to develop the spawned program, it should call
705 * g_win32_get_command_line() to get arguments in UTF-8.
707 * On Windows the low-level child process creation API CreateProcess()
708 * doesn't use argument vectors, but a command line. The C runtime
709 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
710 * eventually calls) paste the argument vector elements together into
711 * a command line, and the C runtime startup code does a corresponding
712 * reconstruction of an argument vector from the command line, to be
713 * passed to main(). Complications arise when you have argument vector
714 * elements that contain spaces or double quotes. The `spawn*()` functions
715 * don't do any quoting or escaping, but on the other hand the startup
716 * code does do unquoting and unescaping in order to enable receiving
717 * arguments with embedded spaces or double quotes. To work around this
718 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
719 * argument vector elements that need it before calling the C runtime
722 * The returned @child_pid on Windows is a handle to the child
723 * process, not its identifier. Process handles and process
724 * identifiers are different concepts on Windows.
726 * @envp is a %NULL-terminated array of strings, where each string
727 * has the form `KEY=VALUE`. This will become the child's environment.
728 * If @envp is %NULL, the child inherits its parent's environment.
730 * @flags should be the bitwise OR of any flags you want to affect the
731 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
732 * child will not automatically be reaped; you must use a child watch
733 * (g_child_watch_add()) to be notified about the death of the child process,
734 * otherwise it will stay around as a zombie process until this process exits.
735 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
736 * free resources which may be associated with the child process. (On Unix,
737 * using a child watch is equivalent to calling waitpid() or handling
738 * the `SIGCHLD` signal manually. On Windows, calling g_spawn_close_pid()
739 * is equivalent to calling CloseHandle() on the process handle returned
740 * in @child_pid). See g_child_watch_add().
742 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
743 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
744 * other open file descriptors will be inherited by the child; otherwise all
745 * descriptors except stdin/stdout/stderr will be closed before calling exec()
746 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
747 * absolute path, it will be looked for in the `PATH` environment
748 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
749 * absolute path, it will be looked for in the `PATH` variable from
750 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
751 * are used, the value from @envp takes precedence over the environment.
753 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
754 * will be discarded, instead of going to the same location as the parent's
755 * standard output. If you use this flag, @stdout_pipe_out must be %NULL.
757 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
758 * will be discarded, instead of going to the same location as the parent's
759 * standard error. If you use this flag, @stderr_pipe_out must be %NULL.
761 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
762 * standard input (by default, the child's standard input is attached to
763 * `/dev/null`). If you use this flag, @stdin_pipe_out must be %NULL.
765 * It is valid to pass the same FD in multiple parameters (e.g. you can pass
766 * a single FD for both @stdout_fd and @stderr_fd, and include it in
769 * @source_fds and @target_fds allow zero or more FDs from this process to be
770 * remapped to different FDs in the spawned process. If @n_fds is greater than
771 * zero, @source_fds and @target_fds must both be non-%NULL and the same length.
772 * Each FD in @source_fds is remapped to the FD number at the same index in
773 * @target_fds. The source and target FD may be equal to simply propagate an FD
774 * to the spawned process. FD remappings are processed after standard FDs, so
775 * any target FDs which equal @stdin_fd, @stdout_fd or @stderr_fd will overwrite
776 * them in the spawned process.
778 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
779 * the file to execute, while the remaining elements are the actual
780 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
781 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
783 * @child_setup and @user_data are a function and user data. On POSIX
784 * platforms, the function is called in the child after GLib has
785 * performed all the setup it plans to perform (including creating
786 * pipes, closing file descriptors, etc.) but before calling exec().
787 * That is, @child_setup is called just before calling exec() in the
788 * child. Obviously actions taken in this function will only affect
789 * the child, not the parent.
791 * On Windows, there is no separate fork() and exec() functionality.
792 * Child processes are created and run with a single API call,
793 * CreateProcess(). There is no sensible thing @child_setup
794 * could be used for on Windows so it is ignored and not called.
796 * If non-%NULL, @child_pid will on Unix be filled with the child's
797 * process ID. You can use the process ID to send signals to the child,
798 * or to use g_child_watch_add() (or waitpid()) if you specified the
799 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
800 * filled with a handle to the child process only if you specified the
801 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
802 * process using the Win32 API, for example wait for its termination
803 * with the WaitFor*() functions, or examine its exit code with
804 * GetExitCodeProcess(). You should close the handle with CloseHandle()
805 * or g_spawn_close_pid() when you no longer need it.
807 * If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out
808 * locations will be filled with file descriptors for writing to the child's
809 * standard input or reading from its standard output or standard error.
810 * The caller of g_spawn_async_with_pipes() must close these file descriptors
811 * when they are no longer in use. If these parameters are %NULL, the
812 * corresponding pipe won't be created.
814 * If @stdin_pipe_out is %NULL, the child's standard input is attached to
815 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
817 * If @stderr_pipe_out is NULL, the child's standard error goes to the same
818 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
821 * If @stdout_pipe_out is NULL, the child's standard output goes to the same
822 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
825 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
826 * If an error is set, the function returns %FALSE. Errors are reported
827 * even if they occur in the child (for example if the executable in
828 * @argv[0] is not found). Typically the `message` field of returned
829 * errors should be displayed to users. Possible errors are those from
830 * the #G_SPAWN_ERROR domain.
832 * If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out,
833 * and @stderr_pipe_out will not be filled with valid values.
835 * If @child_pid is not %NULL and an error does not occur then the returned
836 * process reference must be closed using g_spawn_close_pid().
838 * On modern UNIX platforms, GLib can use an efficient process launching
839 * codepath driven internally by posix_spawn(). This has the advantage of
840 * avoiding the fork-time performance costs of cloning the parent process
841 * address space, and avoiding associated memory overcommit checks that are
842 * not relevant in the context of immediately executing a distinct process.
843 * This optimized codepath will be used provided that the following conditions
846 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
847 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
848 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
849 * 4. @working_directory is %NULL
850 * 5. @child_setup is %NULL
851 * 6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.
853 * If you are writing a GTK+ application, and the program you are spawning is a
854 * graphical application too, then to ensure that the spawned program opens its
855 * windows on the right screen, you may want to use #GdkAppLaunchContext,
856 * #GAppLaunchContext, or set the `DISPLAY` environment variable.
858 * Returns: %TRUE on success, %FALSE if an error was set
863 g_spawn_async_with_pipes_and_fds (const gchar *working_directory,
864 const gchar * const *argv,
865 const gchar * const *envp,
867 GSpawnChildSetupFunc child_setup,
872 const gint *source_fds,
873 const gint *target_fds,
876 gint *stdin_pipe_out,
877 gint *stdout_pipe_out,
878 gint *stderr_pipe_out,
881 g_return_val_if_fail (argv != NULL, FALSE);
882 g_return_val_if_fail (stdout_pipe_out == NULL ||
883 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
884 g_return_val_if_fail (stderr_pipe_out == NULL ||
885 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
886 /* can't inherit stdin if we have an input pipe. */
887 g_return_val_if_fail (stdin_pipe_out == NULL ||
888 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
889 /* can’t use pipes and stdin/stdout/stderr FDs */
890 g_return_val_if_fail (stdin_pipe_out == NULL || stdin_fd < 0, FALSE);
891 g_return_val_if_fail (stdout_pipe_out == NULL || stdout_fd < 0, FALSE);
892 g_return_val_if_fail (stderr_pipe_out == NULL || stderr_fd < 0, FALSE);
894 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
896 (const gchar * const *) argv,
897 (const gchar * const *) envp,
898 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
899 (flags & G_SPAWN_SEARCH_PATH) != 0,
900 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
901 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
902 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
903 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
904 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
905 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
922 * g_spawn_async_with_fds:
923 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
924 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
925 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
926 * @flags: flags from #GSpawnFlags
927 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
928 * @user_data: (closure): user data for @child_setup
929 * @child_pid: (out) (optional): return location for child process ID, or %NULL
930 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
931 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
932 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
933 * @error: return location for error
935 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
936 * so no FD assignments are used.
938 * Returns: %TRUE on success, %FALSE if an error was set
943 g_spawn_async_with_fds (const gchar *working_directory,
947 GSpawnChildSetupFunc child_setup,
955 g_return_val_if_fail (argv != NULL, FALSE);
956 g_return_val_if_fail (stdout_fd < 0 ||
957 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
958 g_return_val_if_fail (stderr_fd < 0 ||
959 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
960 /* can't inherit stdin if we have an input pipe. */
961 g_return_val_if_fail (stdin_fd < 0 ||
962 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
964 return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
966 (const gchar * const *) argv,
967 (const gchar * const *) envp,
968 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
969 (flags & G_SPAWN_SEARCH_PATH) != 0,
970 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
971 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
972 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
973 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
974 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
975 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
988 * g_spawn_command_line_sync:
989 * @command_line: (type filename): a command line
990 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
991 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
992 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
993 * @error: return location for errors
995 * A simple version of g_spawn_sync() with little-used parameters
996 * removed, taking a command line instead of an argument vector. See
997 * g_spawn_sync() for full details. @command_line will be parsed by
998 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
999 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
1000 * implications, so consider using g_spawn_sync() directly if
1001 * appropriate. Possible errors are those from g_spawn_sync() and those
1002 * from g_shell_parse_argv().
1004 * If @exit_status is non-%NULL, the platform-specific exit status of
1005 * the child is stored there; see the documentation of
1006 * g_spawn_check_exit_status() for how to use and interpret this.
1008 * On Windows, please note the implications of g_shell_parse_argv()
1009 * parsing @command_line. Parsing is done according to Unix shell rules, not
1010 * Windows command interpreter rules.
1011 * Space is a separator, and backslashes are
1012 * special. Thus you cannot simply pass a @command_line containing
1013 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
1014 * the backslashes will be eaten, and the space will act as a
1015 * separator. You need to enclose such paths with single quotes, like
1016 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
1018 * Returns: %TRUE on success, %FALSE if an error was set
1021 g_spawn_command_line_sync (const gchar *command_line,
1022 gchar **standard_output,
1023 gchar **standard_error,
1028 gchar **argv = NULL;
1030 g_return_val_if_fail (command_line != NULL, FALSE);
1032 if (!g_shell_parse_argv (command_line,
1037 retval = g_spawn_sync (NULL,
1040 G_SPAWN_SEARCH_PATH,
1053 * g_spawn_command_line_async:
1054 * @command_line: (type filename): a command line
1055 * @error: return location for errors
1057 * A simple version of g_spawn_async() that parses a command line with
1058 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
1059 * command line in the background. Unlike g_spawn_async(), the
1060 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
1061 * that %G_SPAWN_SEARCH_PATH can have security implications, so
1062 * consider using g_spawn_async() directly if appropriate. Possible
1063 * errors are those from g_shell_parse_argv() and g_spawn_async().
1065 * The same concerns on Windows apply as for g_spawn_command_line_sync().
1067 * Returns: %TRUE on success, %FALSE if error is set
1070 g_spawn_command_line_async (const gchar *command_line,
1074 gchar **argv = NULL;
1076 g_return_val_if_fail (command_line != NULL, FALSE);
1078 if (!g_shell_parse_argv (command_line,
1083 retval = g_spawn_async (NULL,
1086 G_SPAWN_SEARCH_PATH,
1097 * g_spawn_check_exit_status:
1098 * @exit_status: An exit code as returned from g_spawn_sync()
1101 * Set @error if @exit_status indicates the child exited abnormally
1102 * (e.g. with a nonzero exit code, or via a fatal signal).
1104 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
1105 * exit status for subprocesses encoded in a platform-specific way.
1106 * On Unix, this is guaranteed to be in the same format waitpid() returns,
1107 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
1109 * Prior to the introduction of this function in GLib 2.34, interpreting
1110 * @exit_status required use of platform-specific APIs, which is problematic
1111 * for software using GLib as a cross-platform layer.
1113 * Additionally, many programs simply want to determine whether or not
1114 * the child exited successfully, and either propagate a #GError or
1115 * print a message to standard error. In that common case, this function
1116 * can be used. Note that the error message in @error will contain
1117 * human-readable information about the exit status.
1119 * The @domain and @code of @error have special semantics in the case
1120 * where the process has an "exit code", as opposed to being killed by
1121 * a signal. On Unix, this happens if WIFEXITED() would be true of
1122 * @exit_status. On Windows, it is always the case.
1124 * The special semantics are that the actual exit code will be the
1125 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1126 * This allows you to differentiate between different exit codes.
1128 * If the process was terminated by some means other than an exit
1129 * status, the domain will be %G_SPAWN_ERROR, and the code will be
1130 * %G_SPAWN_ERROR_FAILED.
1132 * This function just offers convenience; you can of course also check
1133 * the available platform via a macro such as %G_OS_UNIX, and use
1134 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
1135 * to scan or parse the error message string; it may be translated and/or
1136 * change in future versions of GLib.
1138 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1139 * @error will be set)
1144 g_spawn_check_exit_status (gint exit_status,
1147 gboolean ret = FALSE;
1149 if (WIFEXITED (exit_status))
1151 if (WEXITSTATUS (exit_status) != 0)
1153 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
1154 _("Child process exited with code %ld"),
1155 (long) WEXITSTATUS (exit_status));
1159 else if (WIFSIGNALED (exit_status))
1161 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1162 _("Child process killed by signal %ld"),
1163 (long) WTERMSIG (exit_status));
1166 else if (WIFSTOPPED (exit_status))
1168 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1169 _("Child process stopped by signal %ld"),
1170 (long) WSTOPSIG (exit_status));
1175 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1176 _("Child process exited abnormally"));
1185 /* This function is called between fork() and exec() and hence must be
1186 * async-signal-safe (see signal-safety(7)). */
1188 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1190 gchar *buf = (gchar *) vbuf;
1192 while (to_write > 0)
1194 gssize count = write (fd, buf, to_write);
1210 /* This function is called between fork() and exec() and hence must be
1211 * async-signal-safe (see signal-safety(7)). */
1214 write_err_and_exit (gint fd, gint msg)
1218 write_all (fd, &msg, sizeof(msg));
1219 write_all (fd, &en, sizeof(en));
1224 /* This function is called between fork() and exec() and hence must be
1225 * async-signal-safe (see signal-safety(7)). */
1227 set_cloexec (void *data, gint fd)
1229 if (fd >= GPOINTER_TO_INT (data))
1230 fcntl (fd, F_SETFD, FD_CLOEXEC);
1235 /* This function is called between fork() and exec() and hence must be
1236 * async-signal-safe (see signal-safety(7)). */
1238 unset_cloexec (int fd)
1243 flags = fcntl (fd, F_GETFD, 0);
1248 flags &= (~FD_CLOEXEC);
1251 result = fcntl (fd, F_SETFD, flags);
1254 while (result == -1 && errsv == EINTR);
1258 /* This function is called between fork() and exec() and hence must be
1259 * async-signal-safe (see signal-safety(7)). */
1261 dupfd_cloexec (int parent_fd)
1264 #ifdef F_DUPFD_CLOEXEC
1267 fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
1270 while (fd == -1 && errsv == EINTR);
1272 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
1273 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
1278 fd = fcntl (parent_fd, F_DUPFD, 3);
1281 while (fd == -1 && errsv == EINTR);
1282 flags = fcntl (fd, F_GETFD, 0);
1285 flags |= FD_CLOEXEC;
1288 result = fcntl (fd, F_SETFD, flags);
1291 while (result == -1 && errsv == EINTR);
1297 /* This function is called between fork() and exec() and hence must be
1298 * async-signal-safe (see signal-safety(7)). */
1300 safe_close (gint fd)
1306 while (ret < 0 && errno == EINTR);
1311 /* This function is called between fork() and exec() and hence must be
1312 * async-signal-safe (see signal-safety(7)). */
1313 G_GNUC_UNUSED static int
1314 close_func (void *data, int fd)
1316 if (fd >= GPOINTER_TO_INT (data))
1317 (void) safe_close (fd);
1323 struct linux_dirent64
1325 guint64 d_ino; /* 64-bit inode number */
1326 guint64 d_off; /* 64-bit offset to next structure */
1327 unsigned short d_reclen; /* Size of this dirent */
1328 unsigned char d_type; /* File type */
1329 char d_name[]; /* Filename (null-terminated) */
1332 /* This function is called between fork() and exec() and hence must be
1333 * async-signal-safe (see signal-safety(7)). */
1335 filename_to_fd (const char *p)
1339 const int cutoff = G_MAXINT / 10;
1340 const int cutlim = G_MAXINT % 10;
1345 while ((c = *p++) != '\0')
1347 if (c < '0' || c > '9')
1351 /* Check for overflow. */
1352 if (fd > cutoff || (fd == cutoff && c > cutlim))
1362 /* This function is called between fork() and exec() and hence must be
1363 * async-signal-safe (see signal-safety(7)). */
1365 safe_fdwalk (int (*cb)(void *data, int fd), void *data)
1368 /* Use fdwalk function provided by the system if it is known to be
1369 * async-signal safe.
1371 * Currently there are no operating systems known to provide a safe
1372 * implementation, so this section is not used for now.
1374 return fdwalk (cb, data);
1376 /* Fallback implementation of fdwalk. It should be async-signal safe, but it
1377 * may be slow on non-Linux operating systems, especially on systems allowing
1378 * very high number of open file descriptors.
1384 #if 0 && defined(HAVE_SYS_RESOURCE_H)
1389 /* Avoid use of opendir/closedir since these are not async-signal-safe. */
1390 int dir_fd = open ("/proc/self/fd", O_RDONLY | O_DIRECTORY);
1395 struct linux_dirent64 *de;
1397 while ((nread = syscall (SYS_getdents64, dir_fd, buf, sizeof(buf))) > 0)
1399 for (pos = 0; pos < nread; pos += de->d_reclen)
1401 de = (struct linux_dirent64 *)(buf + pos);
1403 fd = filename_to_fd (de->d_name);
1404 if (fd < 0 || fd == dir_fd)
1407 if ((res = cb (data, fd)) != 0)
1412 safe_close (dir_fd);
1416 /* If /proc is not mounted or not accessible we fall back to the old
1421 #if 0 && defined(HAVE_SYS_RESOURCE_H)
1422 /* Use getrlimit() function provided by the system if it is known to be
1423 * async-signal safe.
1425 * Currently there are no operating systems known to provide a safe
1426 * implementation, so this section is not used for now.
1428 if (getrlimit (RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1429 open_max = rl.rlim_max;
1431 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1432 /* Use sysconf() function provided by the system if it is known to be
1433 * async-signal safe.
1435 * FreeBSD: sysconf() is included in the list of async-signal safe functions
1436 * found in https://man.freebsd.org/sigaction(2).
1438 * OpenBSD: sysconf() is included in the list of async-signal safe functions
1439 * found in https://man.openbsd.org/sigaction.2.
1441 * Apple: sysconf() is included in the list of async-signal safe functions
1442 * found in https://opensource.apple.com/source/xnu/xnu-517.12.7/bsd/man/man2/sigaction.2
1445 open_max = sysconf (_SC_OPEN_MAX);
1447 /* Hardcoded fallback: the default process hard limit in Linux as of 2020 */
1451 for (fd = 0; fd < open_max; fd++)
1452 if ((res = cb (data, fd)) != 0)
1459 /* This function is called between fork() and exec() and hence must be
1460 * async-signal-safe (see signal-safety(7)). */
1462 safe_closefrom (int lowfd)
1464 #if defined(__FreeBSD__) || defined(__OpenBSD__)
1465 /* Use closefrom function provided by the system if it is known to be
1466 * async-signal safe.
1468 * FreeBSD: closefrom is included in the list of async-signal safe functions
1469 * found in https://man.freebsd.org/sigaction(2).
1471 * OpenBSD: closefrom is not included in the list, but a direct system call
1472 * should be safe to use.
1474 (void) closefrom (lowfd);
1475 #elif defined(__DragonFly__)
1476 /* It is unclear whether closefrom function included in DragonFlyBSD libc_r
1477 * is safe to use because it calls a lot of library functions. It is also
1478 * unclear whether libc_r itself is still being used. Therefore, we do a
1479 * direct system call here ourselves to avoid possible issues.
1481 (void) syscall (SYS_closefrom, lowfd);
1482 #elif defined(F_CLOSEM)
1483 /* NetBSD and AIX have a special fcntl command which does the same thing as
1484 * closefrom. NetBSD also includes closefrom function, which seems to be a
1485 * simple wrapper of the fcntl command.
1487 (void) fcntl (lowfd, F_CLOSEM);
1490 #if defined(HAVE_CLOSE_RANGE)
1491 /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1492 * around the same time. It was designed for use in async-signal-safe
1493 * situations: https://bugs.python.org/issue38061
1495 * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
1496 * fall back to safe_fdwalk(). */
1497 if (close_range (lowfd, G_MAXUINT) != 0 && errno == ENOSYS)
1498 #endif /* HAVE_CLOSE_RANGE */
1499 (void) safe_fdwalk (close_func, GINT_TO_POINTER (lowfd));
1503 /* This function is called between fork() and exec() and hence must be
1504 * async-signal-safe (see signal-safety(7)). */
1512 while (ret < 0 && (errno == EINTR || errno == EBUSY));
1517 /* This function is called between fork() and exec() and hence must be
1518 * async-signal-safe (see signal-safety(7)). */
1520 safe_dup2 (gint fd1, gint fd2)
1525 ret = dup2 (fd1, fd2);
1526 while (ret < 0 && (errno == EINTR || errno == EBUSY));
1531 /* This function is called between fork() and exec() and hence must be
1532 * async-signal-safe (see signal-safety(7)). */
1534 safe_open (const char *path, gint mode)
1539 ret = open (path, mode);
1540 while (ret < 0 && errno == EINTR);
1553 /* This function is called between fork() and exec() and hence must be
1554 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
1556 do_exec (gint child_err_report_fd,
1561 const gint *target_fds,
1563 const gchar *working_directory,
1564 const gchar * const *argv,
1565 gchar **argv_buffer,
1566 gsize argv_buffer_len,
1567 const gchar * const *envp,
1568 gboolean close_descriptors,
1569 const gchar *search_path,
1570 gchar *search_path_buffer,
1571 gsize search_path_buffer_len,
1572 gboolean stdout_to_null,
1573 gboolean stderr_to_null,
1574 gboolean child_inherits_stdin,
1575 gboolean file_and_argv_zero,
1576 GSpawnChildSetupFunc child_setup,
1581 if (working_directory && chdir (working_directory) < 0)
1582 write_err_and_exit (child_err_report_fd,
1583 CHILD_CHDIR_FAILED);
1585 /* Redirect pipes as required */
1588 /* dup2 can't actually fail here I don't think */
1589 if (safe_dup2 (stdin_fd, 0) < 0)
1590 write_err_and_exit (child_err_report_fd,
1593 if (!((stdout_fd >= 0 || stdout_to_null) && stdin_fd == 1) &&
1594 !((stderr_fd >= 0 || stderr_to_null) && stdin_fd == 2))
1595 set_cloexec (GINT_TO_POINTER(0), stdin_fd);
1597 else if (!child_inherits_stdin)
1599 /* Keep process from blocking on a read of stdin */
1600 gint read_null = safe_open ("/dev/null", O_RDONLY);
1602 write_err_and_exit (child_err_report_fd,
1604 safe_dup2 (read_null, 0);
1605 close_and_invalidate (&read_null);
1610 /* dup2 can't actually fail here I don't think */
1611 if (safe_dup2 (stdout_fd, 1) < 0)
1612 write_err_and_exit (child_err_report_fd,
1615 if (!((stdin_fd >= 0 || !child_inherits_stdin) && stdout_fd == 0) &&
1616 !((stderr_fd >= 0 || stderr_to_null) && stdout_fd == 2))
1617 set_cloexec (GINT_TO_POINTER(0), stdout_fd);
1619 else if (stdout_to_null)
1621 gint write_null = safe_open ("/dev/null", O_WRONLY);
1623 write_err_and_exit (child_err_report_fd,
1625 safe_dup2 (write_null, 1);
1626 close_and_invalidate (&write_null);
1631 /* dup2 can't actually fail here I don't think */
1632 if (safe_dup2 (stderr_fd, 2) < 0)
1633 write_err_and_exit (child_err_report_fd,
1636 if (!((stdin_fd >= 0 || !child_inherits_stdin) && stderr_fd == 0) &&
1637 !((stdout_fd >= 0 || stdout_to_null) && stderr_fd == 1))
1638 set_cloexec (GINT_TO_POINTER(0), stderr_fd);
1640 else if (stderr_to_null)
1642 gint write_null = safe_open ("/dev/null", O_WRONLY);
1644 write_err_and_exit (child_err_report_fd,
1646 safe_dup2 (write_null, 2);
1647 close_and_invalidate (&write_null);
1650 /* Close all file descriptors but stdin, stdout and stderr, and any of source_fds,
1651 * before we exec. Note that this includes
1652 * child_err_report_fd, which keeps the parent from blocking
1653 * forever on the other end of that pipe.
1655 if (close_descriptors)
1657 if (child_setup == NULL && n_fds == 0)
1659 safe_dup2 (child_err_report_fd, 3);
1660 set_cloexec (GINT_TO_POINTER (0), 3);
1662 child_err_report_fd = 3;
1666 safe_fdwalk (set_cloexec, GINT_TO_POINTER (3));
1671 /* We need to do child_err_report_fd anyway */
1672 set_cloexec (GINT_TO_POINTER (0), child_err_report_fd);
1676 * Work through the @source_fds and @target_fds mapping.
1678 * Based on code derived from
1679 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
1680 * used under the LGPLv2+ with permission from author.
1683 /* Basic fd assignments (where source == target) we can just unset FD_CLOEXEC
1685 * If we're doing remapping fd assignments, we need to handle
1686 * the case where the user has specified e.g.:
1689 * We do this by duping the source fds temporarily in a first pass.
1691 * If any of the @target_fds conflict with @child_err_report_fd, dup the
1692 * latter so it doesn’t get conflated.
1696 for (i = 0; i < n_fds; i++)
1698 if (source_fds[i] != target_fds[i])
1699 source_fds[i] = dupfd_cloexec (source_fds[i]);
1701 for (i = 0; i < n_fds; i++)
1703 if (source_fds[i] == target_fds[i])
1705 unset_cloexec (source_fds[i]);
1709 if (target_fds[i] == child_err_report_fd)
1710 child_err_report_fd = safe_dup (child_err_report_fd);
1712 safe_dup2 (source_fds[i], target_fds[i]);
1713 (void) close (source_fds[i]);
1718 /* Call user function just before we exec */
1721 (* child_setup) (user_data);
1725 (gchar **) (file_and_argv_zero ? argv + 1 : argv),
1726 argv_buffer, argv_buffer_len,
1727 (gchar **) envp, search_path, search_path_buffer, search_path_buffer_len);
1730 write_err_and_exit (child_err_report_fd,
1747 if (bytes >= sizeof(gint)*2)
1748 break; /* give up, who knows what happened, should not be
1754 ((gchar*)buf) + bytes,
1755 sizeof(gint) * n_ints_in_buf - bytes);
1756 if (chunk < 0 && errno == EINTR)
1763 /* Some weird shit happened, bail out */
1766 G_SPAWN_ERROR_FAILED,
1767 _("Failed to read from child pipe (%s)"),
1768 g_strerror (errsv));
1772 else if (chunk == 0)
1774 else /* chunk > 0 */
1778 *n_ints_read = (gint)(bytes / sizeof(gint));
1783 #ifdef POSIX_SPAWN_AVAILABLE
1785 do_posix_spawn (const gchar * const *argv,
1786 const gchar * const *envp,
1787 gboolean search_path,
1788 gboolean stdout_to_null,
1789 gboolean stderr_to_null,
1790 gboolean child_inherits_stdin,
1791 gboolean file_and_argv_zero,
1793 gint *child_close_fds,
1799 const gchar * const *argv_pass;
1800 posix_spawnattr_t attr;
1801 posix_spawn_file_actions_t file_actions;
1802 gint parent_close_fds[3];
1803 gint num_parent_close_fds = 0;
1804 GSList *child_close = NULL;
1809 if (*argv[0] == '\0')
1811 /* We check the simple case first. */
1815 r = posix_spawnattr_init (&attr);
1819 if (child_close_fds)
1822 while (child_close_fds[++i] != -1)
1823 child_close = g_slist_prepend (child_close,
1824 GINT_TO_POINTER (child_close_fds[i]));
1827 r = posix_spawnattr_setflags (&attr, POSIX_SPAWN_SETSIGDEF);
1829 goto out_free_spawnattr;
1831 /* Reset some signal handlers that we may use */
1832 sigemptyset (&mask);
1833 sigaddset (&mask, SIGCHLD);
1834 sigaddset (&mask, SIGINT);
1835 sigaddset (&mask, SIGTERM);
1836 sigaddset (&mask, SIGHUP);
1838 r = posix_spawnattr_setsigdefault (&attr, &mask);
1840 goto out_free_spawnattr;
1842 r = posix_spawn_file_actions_init (&file_actions);
1844 goto out_free_spawnattr;
1846 /* Redirect pipes as required */
1850 r = posix_spawn_file_actions_adddup2 (&file_actions, stdin_fd, 0);
1854 if (!g_slist_find (child_close, GINT_TO_POINTER (stdin_fd)))
1855 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdin_fd));
1857 else if (!child_inherits_stdin)
1859 /* Keep process from blocking on a read of stdin */
1860 gint read_null = safe_open ("/dev/null", O_RDONLY | O_CLOEXEC);
1861 g_assert (read_null != -1);
1862 parent_close_fds[num_parent_close_fds++] = read_null;
1864 #ifndef HAVE_O_CLOEXEC
1865 fcntl (read_null, F_SETFD, FD_CLOEXEC);
1868 r = posix_spawn_file_actions_adddup2 (&file_actions, read_null, 0);
1875 r = posix_spawn_file_actions_adddup2 (&file_actions, stdout_fd, 1);
1879 if (!g_slist_find (child_close, GINT_TO_POINTER (stdout_fd)))
1880 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdout_fd));
1882 else if (stdout_to_null)
1884 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1885 g_assert (write_null != -1);
1886 parent_close_fds[num_parent_close_fds++] = write_null;
1888 #ifndef HAVE_O_CLOEXEC
1889 fcntl (write_null, F_SETFD, FD_CLOEXEC);
1892 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 1);
1899 r = posix_spawn_file_actions_adddup2 (&file_actions, stderr_fd, 2);
1903 if (!g_slist_find (child_close, GINT_TO_POINTER (stderr_fd)))
1904 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stderr_fd));
1906 else if (stderr_to_null)
1908 gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1909 g_assert (write_null != -1);
1910 parent_close_fds[num_parent_close_fds++] = write_null;
1912 #ifndef HAVE_O_CLOEXEC
1913 fcntl (write_null, F_SETFD, FD_CLOEXEC);
1916 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 2);
1921 /* Intentionally close the fds in the child as the last file action,
1922 * having been careful not to add the same fd to this list twice.
1924 * This is important to allow (e.g.) for the same fd to be passed as stdout
1925 * and stderr (we must not close it before we have dupped it in both places,
1926 * and we must not attempt to close it twice).
1928 for (elem = child_close; elem != NULL; elem = elem->next)
1930 r = posix_spawn_file_actions_addclose (&file_actions,
1931 GPOINTER_TO_INT (elem->data));
1936 argv_pass = file_and_argv_zero ? argv + 1 : argv;
1938 envp = (const gchar * const *) environ;
1940 /* Don't search when it contains a slash. */
1941 if (!search_path || strchr (argv[0], '/') != NULL)
1942 r = posix_spawn (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
1944 r = posix_spawnp (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
1946 if (r == 0 && child_pid != NULL)
1950 for (i = 0; i < num_parent_close_fds; i++)
1951 close_and_invalidate (&parent_close_fds [i]);
1953 posix_spawn_file_actions_destroy (&file_actions);
1955 posix_spawnattr_destroy (&attr);
1956 g_slist_free (child_close);
1960 #endif /* POSIX_SPAWN_AVAILABLE */
1963 fork_exec (gboolean intermediate_child,
1964 const gchar *working_directory,
1965 const gchar * const *argv,
1966 const gchar * const *envp,
1967 gboolean close_descriptors,
1968 gboolean search_path,
1969 gboolean search_path_from_envp,
1970 gboolean stdout_to_null,
1971 gboolean stderr_to_null,
1972 gboolean child_inherits_stdin,
1973 gboolean file_and_argv_zero,
1974 gboolean cloexec_pipes,
1975 GSpawnChildSetupFunc child_setup,
1978 gint *stdin_pipe_out,
1979 gint *stdout_pipe_out,
1980 gint *stderr_pipe_out,
1984 const gint *source_fds,
1985 const gint *target_fds,
1990 gint child_err_report_pipe[2] = { -1, -1 };
1991 gint child_pid_report_pipe[2] = { -1, -1 };
1992 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1994 const gchar *chosen_search_path;
1995 gchar *search_path_buffer = NULL;
1996 gchar *search_path_buffer_heap = NULL;
1997 gsize search_path_buffer_len = 0;
1998 gchar **argv_buffer = NULL;
1999 gchar **argv_buffer_heap = NULL;
2000 gsize argv_buffer_len = 0;
2001 gint stdin_pipe[2] = { -1, -1 };
2002 gint stdout_pipe[2] = { -1, -1 };
2003 gint stderr_pipe[2] = { -1, -1 };
2004 gint child_close_fds[4] = { -1, -1, -1, -1 };
2005 gint n_child_close_fds = 0;
2006 gint *source_fds_copy = NULL;
2008 g_assert (stdin_pipe_out == NULL || stdin_fd < 0);
2009 g_assert (stdout_pipe_out == NULL || stdout_fd < 0);
2010 g_assert (stderr_pipe_out == NULL || stderr_fd < 0);
2012 /* If pipes have been requested, open them */
2013 if (stdin_pipe_out != NULL)
2015 if (!g_unix_open_pipe (stdin_pipe, pipe_flags, error))
2016 goto cleanup_and_fail;
2017 child_close_fds[n_child_close_fds++] = stdin_pipe[1];
2018 stdin_fd = stdin_pipe[0];
2021 if (stdout_pipe_out != NULL)
2023 if (!g_unix_open_pipe (stdout_pipe, pipe_flags, error))
2024 goto cleanup_and_fail;
2025 child_close_fds[n_child_close_fds++] = stdout_pipe[0];
2026 stdout_fd = stdout_pipe[1];
2029 if (stderr_pipe_out != NULL)
2031 if (!g_unix_open_pipe (stderr_pipe, pipe_flags, error))
2032 goto cleanup_and_fail;
2033 child_close_fds[n_child_close_fds++] = stderr_pipe[0];
2034 stderr_fd = stderr_pipe[1];
2037 child_close_fds[n_child_close_fds++] = -1;
2039 #ifdef POSIX_SPAWN_AVAILABLE
2040 /* FIXME: Handle @source_fds and @target_fds in do_posix_spawn() using the
2041 * file actions API. */
2042 if (!intermediate_child && working_directory == NULL && !close_descriptors &&
2043 !search_path_from_envp && child_setup == NULL && n_fds == 0)
2045 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2046 "GLib", "posix_spawn",
2049 status = do_posix_spawn (argv,
2054 child_inherits_stdin,
2064 if (status != ENOEXEC)
2068 G_SPAWN_ERROR_FAILED,
2069 _("Failed to spawn child process “%s” (%s)"),
2071 g_strerror (status));
2072 goto cleanup_and_fail;
2075 /* posix_spawn is not intended to support script execution. It does in
2076 * some situations on some glibc versions, but that will be fixed.
2077 * So if it fails with ENOEXEC, we fall through to the regular
2078 * gspawn codepath so that script execution can be attempted,
2079 * per standard gspawn behaviour. */
2080 g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
2084 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2086 "posix_spawn avoided %s%s%s%s%s",
2087 !intermediate_child ? "" : "(automatic reaping requested) ",
2088 working_directory == NULL ? "" : "(workdir specified) ",
2089 !close_descriptors ? "" : "(fd close requested) ",
2090 !search_path_from_envp ? "" : "(using envp for search path) ",
2091 child_setup == NULL ? "" : "(child_setup specified) ");
2093 #endif /* POSIX_SPAWN_AVAILABLE */
2095 /* Choose a search path. This has to be done before calling fork()
2096 * as getenv() isn’t async-signal-safe (see `man 7 signal-safety`). */
2097 chosen_search_path = NULL;
2098 if (search_path_from_envp)
2099 chosen_search_path = g_environ_getenv ((gchar **) envp, "PATH");
2100 if (search_path && chosen_search_path == NULL)
2101 chosen_search_path = g_getenv ("PATH");
2103 if ((search_path || search_path_from_envp) && chosen_search_path == NULL)
2105 /* There is no 'PATH' in the environment. The default
2106 * * search path in libc is the current directory followed by
2107 * * the path 'confstr' returns for '_CS_PATH'.
2110 /* In GLib we put . last, for security, and don't use the
2111 * * unportable confstr(); UNIX98 does not actually specify
2112 * * what to search if PATH is unset. POSIX may, dunno.
2115 chosen_search_path = "/bin:/usr/bin:.";
2118 if (search_path || search_path_from_envp)
2119 g_assert (chosen_search_path != NULL);
2121 g_assert (chosen_search_path == NULL);
2123 /* Allocate a buffer which the fork()ed child can use to assemble potential
2124 * paths for the binary to exec(), combining the argv[0] and elements from
2125 * the chosen_search_path. This can’t be done in the child because malloc()
2126 * (or alloca()) are not async-signal-safe (see `man 7 signal-safety`).
2128 * Add 2 for the nul terminator and a leading `/`. */
2129 if (chosen_search_path != NULL)
2131 search_path_buffer_len = strlen (chosen_search_path) + strlen (argv[0]) + 2;
2132 if (search_path_buffer_len < 4000)
2134 /* Prefer small stack allocations to avoid valgrind leak warnings
2135 * in forked child. The 4000B cutoff is arbitrary. */
2136 search_path_buffer = g_alloca (search_path_buffer_len);
2140 search_path_buffer_heap = g_malloc (search_path_buffer_len);
2141 search_path_buffer = search_path_buffer_heap;
2145 if (search_path || search_path_from_envp)
2146 g_assert (search_path_buffer != NULL);
2148 g_assert (search_path_buffer == NULL);
2150 /* And allocate a buffer which is 2 elements longer than @argv, so that if
2151 * script_execute() has to be called later on, it can build a wrapper argv
2152 * array in this buffer. */
2153 argv_buffer_len = g_strv_length ((gchar **) argv) + 2;
2154 if (argv_buffer_len < 4000 / sizeof (gchar *))
2156 /* Prefer small stack allocations to avoid valgrind leak warnings
2157 * in forked child. The 4000B cutoff is arbitrary. */
2158 argv_buffer = g_newa (gchar *, argv_buffer_len);
2162 argv_buffer_heap = g_new (gchar *, argv_buffer_len);
2163 argv_buffer = argv_buffer_heap;
2166 /* And one to hold a copy of @source_fds for later manipulation in do_exec(). */
2167 source_fds_copy = g_new (int, n_fds);
2169 memcpy (source_fds_copy, source_fds, sizeof (*source_fds) * n_fds);
2171 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
2172 goto cleanup_and_fail;
2174 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
2175 goto cleanup_and_fail;
2186 _("Failed to fork (%s)"),
2187 g_strerror (errsv));
2189 goto cleanup_and_fail;
2193 /* Immediate child. This may or may not be the child that
2194 * actually execs the new process.
2197 /* Reset some signal handlers that we may use */
2198 signal (SIGCHLD, SIG_DFL);
2199 signal (SIGINT, SIG_DFL);
2200 signal (SIGTERM, SIG_DFL);
2201 signal (SIGHUP, SIG_DFL);
2203 /* Be sure we crash if the parent exits
2204 * and we write to the err_report_pipe
2206 signal (SIGPIPE, SIG_DFL);
2208 /* Close the parent's end of the pipes;
2209 * not needed in the close_descriptors case,
2212 close_and_invalidate (&child_err_report_pipe[0]);
2213 close_and_invalidate (&child_pid_report_pipe[0]);
2214 if (child_close_fds[0] != -1)
2217 while (child_close_fds[++i] != -1)
2218 close_and_invalidate (&child_close_fds[i]);
2221 if (intermediate_child)
2223 /* We need to fork an intermediate child that launches the
2224 * final child. The purpose of the intermediate child
2225 * is to exit, so we can waitpid() it immediately.
2226 * Then the grandchild will not become a zombie.
2228 GPid grandchild_pid;
2230 grandchild_pid = fork ();
2232 if (grandchild_pid < 0)
2234 /* report -1 as child PID */
2235 write_all (child_pid_report_pipe[1], &grandchild_pid,
2236 sizeof(grandchild_pid));
2238 write_err_and_exit (child_err_report_pipe[1],
2241 else if (grandchild_pid == 0)
2243 close_and_invalidate (&child_pid_report_pipe[1]);
2244 do_exec (child_err_report_pipe[1],
2259 search_path_buffer_len,
2262 child_inherits_stdin,
2269 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
2270 close_and_invalidate (&child_pid_report_pipe[1]);
2277 /* Just run the child.
2280 do_exec (child_err_report_pipe[1],
2295 search_path_buffer_len,
2298 child_inherits_stdin,
2311 /* Close the uncared-about ends of the pipes */
2312 close_and_invalidate (&child_err_report_pipe[1]);
2313 close_and_invalidate (&child_pid_report_pipe[1]);
2315 /* If we had an intermediate child, reap it */
2316 if (intermediate_child)
2319 if (waitpid (pid, &status, 0) < 0)
2323 else if (errno == ECHILD)
2324 ; /* do nothing, child already reaped */
2326 g_warning ("waitpid() should not fail in 'fork_exec'");
2331 if (!read_ints (child_err_report_pipe[0],
2334 goto cleanup_and_fail;
2338 /* Error from the child. */
2342 case CHILD_CHDIR_FAILED:
2345 G_SPAWN_ERROR_CHDIR,
2346 _("Failed to change to directory “%s” (%s)"),
2348 g_strerror (buf[1]));
2352 case CHILD_EXEC_FAILED:
2355 _g_spawn_exec_err_to_g_error (buf[1]),
2356 _("Failed to execute child process “%s” (%s)"),
2358 g_strerror (buf[1]));
2362 case CHILD_DUP2_FAILED:
2365 G_SPAWN_ERROR_FAILED,
2366 _("Failed to redirect output or input of child process (%s)"),
2367 g_strerror (buf[1]));
2371 case CHILD_FORK_FAILED:
2375 _("Failed to fork child process (%s)"),
2376 g_strerror (buf[1]));
2382 G_SPAWN_ERROR_FAILED,
2383 _("Unknown error executing child process “%s”"),
2388 goto cleanup_and_fail;
2391 /* Get child pid from intermediate child pipe. */
2392 if (intermediate_child)
2396 if (!read_ints (child_pid_report_pipe[0],
2397 buf, 1, &n_ints, error))
2398 goto cleanup_and_fail;
2406 G_SPAWN_ERROR_FAILED,
2407 _("Failed to read enough data from child pid pipe (%s)"),
2408 g_strerror (errsv));
2409 goto cleanup_and_fail;
2413 /* we have the child pid */
2418 /* Success against all odds! return the information */
2419 close_and_invalidate (&child_err_report_pipe[0]);
2420 close_and_invalidate (&child_pid_report_pipe[0]);
2422 g_free (search_path_buffer_heap);
2423 g_free (argv_buffer_heap);
2424 g_free (source_fds_copy);
2433 /* Close the uncared-about ends of the pipes */
2434 close_and_invalidate (&stdin_pipe[0]);
2435 close_and_invalidate (&stdout_pipe[1]);
2436 close_and_invalidate (&stderr_pipe[1]);
2438 if (stdin_pipe_out != NULL)
2439 *stdin_pipe_out = steal_fd (&stdin_pipe[1]);
2441 if (stdout_pipe_out != NULL)
2442 *stdout_pipe_out = steal_fd (&stdout_pipe[0]);
2444 if (stderr_pipe_out != NULL)
2445 *stderr_pipe_out = steal_fd (&stderr_pipe[0]);
2451 /* There was an error from the Child, reap the child to avoid it being
2458 if (waitpid (pid, NULL, 0) < 0)
2462 else if (errno == ECHILD)
2463 ; /* do nothing, child already reaped */
2465 g_warning ("waitpid() should not fail in 'fork_exec'");
2469 close_and_invalidate (&stdin_pipe[0]);
2470 close_and_invalidate (&stdin_pipe[1]);
2471 close_and_invalidate (&stdout_pipe[0]);
2472 close_and_invalidate (&stdout_pipe[1]);
2473 close_and_invalidate (&stderr_pipe[0]);
2474 close_and_invalidate (&stderr_pipe[1]);
2476 close_and_invalidate (&child_err_report_pipe[0]);
2477 close_and_invalidate (&child_err_report_pipe[1]);
2478 close_and_invalidate (&child_pid_report_pipe[0]);
2479 close_and_invalidate (&child_pid_report_pipe[1]);
2481 g_clear_pointer (&search_path_buffer_heap, g_free);
2482 g_clear_pointer (&argv_buffer_heap, g_free);
2483 g_clear_pointer (&source_fds_copy, g_free);
2488 /* Based on execvp from GNU C Library */
2490 /* This function is called between fork() and exec() and hence must be
2491 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2493 script_execute (const gchar *file,
2495 gchar **argv_buffer,
2496 gsize argv_buffer_len,
2499 /* Count the arguments. */
2504 /* Construct an argument list for the shell. */
2505 if (argc + 2 > argv_buffer_len)
2508 argv_buffer[0] = (char *) "/bin/sh";
2509 argv_buffer[1] = (char *) file;
2512 argv_buffer[argc + 1] = argv[argc];
2516 /* Execute the shell. */
2518 execve (argv_buffer[0], argv_buffer, envp);
2520 execv (argv_buffer[0], argv_buffer);
2525 /* This function is called between fork() and exec() and hence must be
2526 * async-signal-safe (see signal-safety(7)). */
2528 my_strchrnul (const gchar *str, gchar c)
2530 gchar *p = (gchar*) str;
2531 while (*p && (*p != c))
2537 /* This function is called between fork() and exec() and hence must be
2538 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2540 g_execute (const gchar *file,
2542 gchar **argv_buffer,
2543 gsize argv_buffer_len,
2545 const gchar *search_path,
2546 gchar *search_path_buffer,
2547 gsize search_path_buffer_len)
2551 /* We check the simple case first. */
2556 if (search_path == NULL || strchr (file, '/') != NULL)
2558 /* Don't search when it contains a slash. */
2560 execve (file, argv, envp);
2564 if (errno == ENOEXEC &&
2565 !script_execute (file, argv, argv_buffer, argv_buffer_len, envp))
2573 gboolean got_eacces = 0;
2574 const gchar *path, *p;
2580 len = strlen (file) + 1;
2581 pathlen = strlen (path);
2582 name = search_path_buffer;
2584 if (search_path_buffer_len < pathlen + len + 1)
2590 /* Copy the file name at the top, including '\0' */
2591 memcpy (name + pathlen + 1, file, len);
2592 name = name + pathlen;
2593 /* And add the slash before the filename */
2602 p = my_strchrnul (path, ':');
2605 /* Two adjacent colons, or a colon at the beginning or the end
2606 * of 'PATH' means to search the current directory.
2610 startp = memcpy (name - (p - path), path, p - path);
2612 /* Try to execute this name. If it works, execv will not return. */
2614 execve (startp, argv, envp);
2616 execv (startp, argv);
2618 if (errno == ENOEXEC &&
2619 !script_execute (startp, argv, argv_buffer, argv_buffer_len, envp))
2628 /* Record the we got a 'Permission denied' error. If we end
2629 * up finding no executable we can use, we want to diagnose
2630 * that we did find one but were denied access.
2642 /* Those errors indicate the file is missing or not executable
2643 * by us, in which case we want to just try the next path
2650 /* Some strange filesystems like AFS return even
2651 * stranger error numbers. They cannot reasonably mean anything
2652 * else so ignore those, too.
2657 /* Some other error means we found an executable file, but
2658 * something went wrong executing it; return the error to our
2664 while (*p++ != '\0');
2666 /* We tried every element and none of them worked. */
2668 /* At least one failure was due to permissions, so report that
2674 /* Return the error from the last attempt (probably ENOENT). */
2679 * g_spawn_close_pid:
2680 * @pid: The process reference to close
2682 * On some platforms, notably Windows, the #GPid type represents a resource
2683 * which must be closed to prevent resource leaking. g_spawn_close_pid()
2684 * is provided for this purpose. It should be used on all platforms, even
2685 * though it doesn't do anything under UNIX.
2688 g_spawn_close_pid (GPid pid)