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 */
35 #ifdef HAVE_CRT_EXTERNS_H
36 #include <crt_externs.h> /* for _NSGetEnviron */
39 #ifdef HAVE_SYS_SELECT_H
40 #include <sys/select.h>
41 #endif /* HAVE_SYS_SELECT_H */
43 #ifdef HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif /* HAVE_SYS_RESOURCE_H */
48 #include "gspawn-private.h"
50 #include "glib/gstdio.h"
56 #include "gstrfuncs.h"
57 #include "gtestutils.h"
60 #include "glib-unix.h"
62 /* posix_spawn() is assumed the fastest way to spawn, but glibc's
63 * implementation was buggy before glibc 2.24, so avoid it on old versions.
65 #ifdef HAVE_POSIX_SPAWN
68 #if __GLIBC_PREREQ(2,24)
69 #define POSIX_SPAWN_AVAILABLE
72 #else /* !__GLIBC__ */
73 /* Assume that all non-glibc posix_spawn implementations are fine. */
74 #define POSIX_SPAWN_AVAILABLE
75 #endif /* __GLIBC__ */
76 #endif /* HAVE_POSIX_SPAWN */
78 #ifdef HAVE__NSGETENVIRON
79 #define environ (*_NSGetEnviron())
81 extern char **environ
;
86 * @Short_description: process launching
87 * @Title: Spawning Processes
89 * GLib supports spawning of processes with an API that is more
90 * convenient than the bare UNIX fork() and exec().
92 * The g_spawn family of functions has synchronous (g_spawn_sync())
93 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
94 * as well as convenience variants that take a complete shell-like
95 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
97 * See #GSubprocess in GIO for a higher-level API that provides
98 * stream interfaces for communication with child processes.
100 * An example of using g_spawn_async_with_pipes():
101 * |[<!-- language="C" -->
102 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
103 * gint child_stdout, child_stderr;
105 * g_autoptr(GError) error = NULL;
107 * // Spawn child process.
108 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
109 * NULL, &child_pid, NULL, &child_stdout,
110 * &child_stderr, &error);
113 * g_error ("Spawning child failed: %s", error->message);
117 * // Add a child watch function which will be called when the child process
119 * g_child_watch_add (child_pid, child_watch_cb, NULL);
121 * // You could watch for output on @child_stdout and @child_stderr using
122 * // #GUnixInputStream or #GIOChannel here.
125 * child_watch_cb (GPid pid,
127 * gpointer user_data)
129 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
130 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
132 * // Free any resources associated with the child here, such as I/O channels
133 * // on its stdout and stderr FDs. If you have no code to put in the
134 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
135 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
136 * // otherwise the child process will stay around as a zombie until this
139 * g_spawn_close_pid (pid);
146 static gint
g_execute (const gchar
*file
,
149 gboolean search_path
,
150 gboolean search_path_from_envp
);
152 static gboolean
fork_exec_with_pipes (gboolean intermediate_child
,
153 const gchar
*working_directory
,
156 gboolean close_descriptors
,
157 gboolean search_path
,
158 gboolean search_path_from_envp
,
159 gboolean stdout_to_null
,
160 gboolean stderr_to_null
,
161 gboolean child_inherits_stdin
,
162 gboolean file_and_argv_zero
,
163 gboolean cloexec_pipes
,
164 GSpawnChildSetupFunc child_setup
,
167 gint
*standard_input
,
168 gint
*standard_output
,
169 gint
*standard_error
,
172 static gboolean
fork_exec_with_fds (gboolean intermediate_child
,
173 const gchar
*working_directory
,
176 gboolean close_descriptors
,
177 gboolean search_path
,
178 gboolean search_path_from_envp
,
179 gboolean stdout_to_null
,
180 gboolean stderr_to_null
,
181 gboolean child_inherits_stdin
,
182 gboolean file_and_argv_zero
,
183 gboolean cloexec_pipes
,
184 GSpawnChildSetupFunc child_setup
,
187 gint
*child_close_fds
,
193 G_DEFINE_QUARK (g
-exec
-error
-quark
, g_spawn_error
)
194 G_DEFINE_QUARK (g
-spawn
-exit
-error
-quark
, g_spawn_exit_error
)
198 * @working_directory: (type filename) (nullable): child's current working
199 * directory, or %NULL to inherit parent's
200 * @argv: (array zero-terminated=1) (element-type filename):
201 * child's argument vector
202 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
203 * child's environment, or %NULL to inherit parent's
204 * @flags: flags from #GSpawnFlags
205 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
206 * @user_data: (closure): user data for @child_setup
207 * @child_pid: (out) (optional): return location for child process reference, or %NULL
208 * @error: return location for error
210 * See g_spawn_async_with_pipes() for a full description; this function
211 * simply calls the g_spawn_async_with_pipes() without any pipes.
213 * You should call g_spawn_close_pid() on the returned child process
214 * reference when you don't need it any more.
216 * If you are writing a GTK+ application, and the program you are spawning is a
217 * graphical application too, then to ensure that the spawned program opens its
218 * windows on the right screen, you may want to use #GdkAppLaunchContext,
219 * #GAppLaunchContext, or set the %DISPLAY environment variable.
221 * Note that the returned @child_pid on Windows is a handle to the child
222 * process and not its identifier. Process handles and process identifiers
223 * are different concepts on Windows.
225 * Returns: %TRUE on success, %FALSE if error is set
228 g_spawn_async (const gchar
*working_directory
,
232 GSpawnChildSetupFunc child_setup
,
237 g_return_val_if_fail (argv
!= NULL
, FALSE
);
239 return g_spawn_async_with_pipes (working_directory
,
249 /* Avoids a danger in threaded situations (calling close()
250 * on a file descriptor twice, and another thread has
251 * re-opened it since the first close)
254 close_and_invalidate (gint
*fd
)
260 (void) g_close (*fd
, NULL
);
265 /* Some versions of OS X define READ_OK in public headers */
270 READ_FAILED
= 0, /* FALSE */
276 read_data (GString
*str
,
284 bytes
= read (fd
, buf
, 4096);
290 g_string_append_len (str
, buf
, bytes
);
293 else if (errno
== EINTR
)
302 _("Failed to read data from child process (%s)"),
311 * @working_directory: (type filename) (nullable): child's current working
312 * directory, or %NULL to inherit parent's
313 * @argv: (array zero-terminated=1) (element-type filename):
314 * child's argument vector
315 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
316 * child's environment, or %NULL to inherit parent's
317 * @flags: flags from #GSpawnFlags
318 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
319 * @user_data: (closure): user data for @child_setup
320 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
321 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
322 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
323 * @error: return location for error, or %NULL
325 * Executes a child synchronously (waits for the child to exit before returning).
326 * All output from the child is stored in @standard_output and @standard_error,
327 * if those parameters are non-%NULL. Note that you must set the
328 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
329 * passing %NULL for @standard_output and @standard_error.
331 * If @exit_status is non-%NULL, the platform-specific exit status of
332 * the child is stored there; see the documentation of
333 * g_spawn_check_exit_status() for how to use and interpret this.
334 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
335 * @flags, and on POSIX platforms, the same restrictions as for
336 * g_child_watch_source_new() apply.
338 * If an error occurs, no data is returned in @standard_output,
339 * @standard_error, or @exit_status.
341 * This function calls g_spawn_async_with_pipes() internally; see that
342 * function for full details on the other parameters and details on
343 * how these functions work on Windows.
345 * Returns: %TRUE on success, %FALSE if an error was set
348 g_spawn_sync (const gchar
*working_directory
,
352 GSpawnChildSetupFunc child_setup
,
354 gchar
**standard_output
,
355 gchar
**standard_error
,
364 GString
*outstr
= NULL
;
365 GString
*errstr
= NULL
;
369 g_return_val_if_fail (argv
!= NULL
, FALSE
);
370 g_return_val_if_fail (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
), FALSE
);
371 g_return_val_if_fail (standard_output
== NULL
||
372 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
373 g_return_val_if_fail (standard_error
== NULL
||
374 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
376 /* Just to ensure segfaults if callers try to use
377 * these when an error is reported.
380 *standard_output
= NULL
;
383 *standard_error
= NULL
;
385 if (!fork_exec_with_pipes (FALSE
,
389 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
390 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
391 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
392 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
393 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
394 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
395 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
396 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
401 standard_output
? &outpipe
: NULL
,
402 standard_error
? &errpipe
: NULL
,
406 /* Read data from child. */
412 outstr
= g_string_new (NULL
);
417 errstr
= g_string_new (NULL
);
420 /* Read data until we get EOF on both pipes. */
429 FD_SET (outpipe
, &fds
);
431 FD_SET (errpipe
, &fds
);
433 ret
= select (MAX (outpipe
, errpipe
) + 1,
436 NULL
/* no timeout */);
450 _("Unexpected error in select() reading data from a child process (%s)"),
456 if (outpipe
>= 0 && FD_ISSET (outpipe
, &fds
))
458 switch (read_data (outstr
, outpipe
, error
))
464 close_and_invalidate (&outpipe
);
475 if (errpipe
>= 0 && FD_ISSET (errpipe
, &fds
))
477 switch (read_data (errstr
, errpipe
, error
))
483 close_and_invalidate (&errpipe
);
495 /* These should only be open still if we had an error. */
498 close_and_invalidate (&outpipe
);
500 close_and_invalidate (&errpipe
);
502 /* Wait for child to exit, even if we have
507 ret
= waitpid (pid
, &status
, 0);
513 else if (errno
== ECHILD
)
517 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.");
521 /* We don't need the exit status. */
526 if (!failed
) /* avoid error pileups */
535 _("Unexpected error in waitpid() (%s)"),
544 g_string_free (outstr
, TRUE
);
546 g_string_free (errstr
, TRUE
);
553 *exit_status
= status
;
556 *standard_output
= g_string_free (outstr
, FALSE
);
559 *standard_error
= g_string_free (errstr
, FALSE
);
566 * g_spawn_async_with_pipes:
567 * @working_directory: (type filename) (nullable): child's current working
568 * directory, or %NULL to inherit parent's, in the GLib file name encoding
569 * @argv: (array zero-terminated=1) (element-type filename): child's argument
570 * vector, in the GLib file name encoding
571 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
572 * child's environment, or %NULL to inherit parent's, in the GLib file
574 * @flags: flags from #GSpawnFlags
575 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
576 * @user_data: (closure): user data for @child_setup
577 * @child_pid: (out) (optional): return location for child process ID, or %NULL
578 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
579 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
580 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
581 * @error: return location for error
583 * Executes a child program asynchronously (your program will not
584 * block waiting for the child to exit). The child program is
585 * specified by the only argument that must be provided, @argv.
586 * @argv should be a %NULL-terminated array of strings, to be passed
587 * as the argument vector for the child. The first string in @argv
588 * is of course the name of the program to execute. By default, the
589 * name of the program must be a full path. If @flags contains the
590 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
591 * used to search for the executable. If @flags contains the
592 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
593 * @envp is used to search for the executable. If both the
594 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
595 * are set, the `PATH` variable from @envp takes precedence over
596 * the environment variable.
598 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
599 * used, then the program will be run from the current directory (or
600 * @working_directory, if specified); this might be unexpected or even
601 * dangerous in some cases when the current directory is world-writable.
603 * On Windows, note that all the string or string vector arguments to
604 * this function and the other g_spawn*() functions are in UTF-8, the
605 * GLib file name encoding. Unicode characters that are not part of
606 * the system codepage passed in these arguments will be correctly
607 * available in the spawned program only if it uses wide character API
608 * to retrieve its command line. For C programs built with Microsoft's
609 * tools it is enough to make the program have a wmain() instead of
610 * main(). wmain() has a wide character argument vector as parameter.
612 * At least currently, mingw doesn't support wmain(), so if you use
613 * mingw to develop the spawned program, it should call
614 * g_win32_get_command_line() to get arguments in UTF-8.
616 * On Windows the low-level child process creation API CreateProcess()
617 * doesn't use argument vectors, but a command line. The C runtime
618 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
619 * eventually calls) paste the argument vector elements together into
620 * a command line, and the C runtime startup code does a corresponding
621 * reconstruction of an argument vector from the command line, to be
622 * passed to main(). Complications arise when you have argument vector
623 * elements that contain spaces of double quotes. The spawn*() functions
624 * don't do any quoting or escaping, but on the other hand the startup
625 * code does do unquoting and unescaping in order to enable receiving
626 * arguments with embedded spaces or double quotes. To work around this
627 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
628 * argument vector elements that need it before calling the C runtime
631 * The returned @child_pid on Windows is a handle to the child
632 * process, not its identifier. Process handles and process
633 * identifiers are different concepts on Windows.
635 * @envp is a %NULL-terminated array of strings, where each string
636 * has the form `KEY=VALUE`. This will become the child's environment.
637 * If @envp is %NULL, the child inherits its parent's environment.
639 * @flags should be the bitwise OR of any flags you want to affect the
640 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
641 * child will not automatically be reaped; you must use a child watch
642 * (g_child_watch_add()) to be notified about the death of the child process,
643 * otherwise it will stay around as a zombie process until this process exits.
644 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
645 * free resources which may be associated with the child process. (On Unix,
646 * using a child watch is equivalent to calling waitpid() or handling
647 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
648 * is equivalent to calling CloseHandle() on the process handle returned
649 * in @child_pid). See g_child_watch_add().
651 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
652 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
653 * other open file descriptors will be inherited by the child; otherwise all
654 * descriptors except stdin/stdout/stderr will be closed before calling exec()
655 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
656 * absolute path, it will be looked for in the `PATH` environment
657 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
658 * absolute path, it will be looked for in the `PATH` variable from
659 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
660 * are used, the value from @envp takes precedence over the environment.
661 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
662 * will be discarded, instead of going to the same location as the parent's
663 * standard output. If you use this flag, @standard_output must be %NULL.
664 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
665 * will be discarded, instead of going to the same location as the parent's
666 * standard error. If you use this flag, @standard_error must be %NULL.
667 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
668 * standard input (by default, the child's standard input is attached to
669 * `/dev/null`). If you use this flag, @standard_input must be %NULL.
670 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
671 * the file to execute, while the remaining elements are the actual
672 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
673 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
675 * @child_setup and @user_data are a function and user data. On POSIX
676 * platforms, the function is called in the child after GLib has
677 * performed all the setup it plans to perform (including creating
678 * pipes, closing file descriptors, etc.) but before calling exec().
679 * That is, @child_setup is called just before calling exec() in the
680 * child. Obviously actions taken in this function will only affect
681 * the child, not the parent.
683 * On Windows, there is no separate fork() and exec() functionality.
684 * Child processes are created and run with a single API call,
685 * CreateProcess(). There is no sensible thing @child_setup
686 * could be used for on Windows so it is ignored and not called.
688 * If non-%NULL, @child_pid will on Unix be filled with the child's
689 * process ID. You can use the process ID to send signals to the child,
690 * or to use g_child_watch_add() (or waitpid()) if you specified the
691 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
692 * filled with a handle to the child process only if you specified the
693 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
694 * process using the Win32 API, for example wait for its termination
695 * with the WaitFor*() functions, or examine its exit code with
696 * GetExitCodeProcess(). You should close the handle with CloseHandle()
697 * or g_spawn_close_pid() when you no longer need it.
699 * If non-%NULL, the @standard_input, @standard_output, @standard_error
700 * locations will be filled with file descriptors for writing to the child's
701 * standard input or reading from its standard output or standard error.
702 * The caller of g_spawn_async_with_pipes() must close these file descriptors
703 * when they are no longer in use. If these parameters are %NULL, the
704 * corresponding pipe won't be created.
706 * If @standard_input is %NULL, the child's standard input is attached to
707 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
709 * If @standard_error is NULL, the child's standard error goes to the same
710 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
713 * If @standard_output is NULL, the child's standard output goes to the same
714 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
717 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
718 * If an error is set, the function returns %FALSE. Errors are reported
719 * even if they occur in the child (for example if the executable in
720 * @argv[0] is not found). Typically the `message` field of returned
721 * errors should be displayed to users. Possible errors are those from
722 * the #G_SPAWN_ERROR domain.
724 * If an error occurs, @child_pid, @standard_input, @standard_output,
725 * and @standard_error will not be filled with valid values.
727 * If @child_pid is not %NULL and an error does not occur then the returned
728 * process reference must be closed using g_spawn_close_pid().
730 * On modern UNIX platforms, GLib can use an efficient process launching
731 * codepath driven internally by posix_spawn(). This has the advantage of
732 * avoiding the fork-time performance costs of cloning the parent process
733 * address space, and avoiding associated memory overcommit checks that are
734 * not relevant in the context of immediately executing a distinct process.
735 * This optimized codepath will be used provided that the following conditions
738 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
739 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
740 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
741 * 4. @working_directory is %NULL
742 * 5. @child_setup is %NULL
743 * 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.
745 * If you are writing a GTK+ application, and the program you are spawning is a
746 * graphical application too, then to ensure that the spawned program opens its
747 * windows on the right screen, you may want to use #GdkAppLaunchContext,
748 * #GAppLaunchContext, or set the %DISPLAY environment variable.
750 * Returns: %TRUE on success, %FALSE if an error was set
753 g_spawn_async_with_pipes (const gchar
*working_directory
,
757 GSpawnChildSetupFunc child_setup
,
760 gint
*standard_input
,
761 gint
*standard_output
,
762 gint
*standard_error
,
765 g_return_val_if_fail (argv
!= NULL
, FALSE
);
766 g_return_val_if_fail (standard_output
== NULL
||
767 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
768 g_return_val_if_fail (standard_error
== NULL
||
769 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
770 /* can't inherit stdin if we have an input pipe. */
771 g_return_val_if_fail (standard_input
== NULL
||
772 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
774 return fork_exec_with_pipes (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
778 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
779 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
780 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
781 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
782 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
783 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
784 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
785 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
796 * g_spawn_async_with_fds:
797 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
798 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
799 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
800 * @flags: flags from #GSpawnFlags
801 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
802 * @user_data: (closure): user data for @child_setup
803 * @child_pid: (out) (optional): return location for child process ID, or %NULL
804 * @stdin_fd: file descriptor to use for child's stdin, or -1
805 * @stdout_fd: file descriptor to use for child's stdout, or -1
806 * @stderr_fd: file descriptor to use for child's stderr, or -1
807 * @error: return location for error
809 * Identical to g_spawn_async_with_pipes() but instead of
810 * creating pipes for the stdin/stdout/stderr, you can pass existing
811 * file descriptors into this function through the @stdin_fd,
812 * @stdout_fd and @stderr_fd parameters. The following @flags
813 * also have their behaviour slightly tweaked as a result:
815 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
816 * will be discarded, instead of going to the same location as the parent's
817 * standard output. If you use this flag, @standard_output must be -1.
818 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
819 * will be discarded, instead of going to the same location as the parent's
820 * standard error. If you use this flag, @standard_error must be -1.
821 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
822 * standard input (by default, the child's standard input is attached to
823 * /dev/null). If you use this flag, @standard_input must be -1.
825 * It is valid to pass the same fd in multiple parameters (e.g. you can pass
826 * a single fd for both stdout and stderr).
828 * Returns: %TRUE on success, %FALSE if an error was set
833 g_spawn_async_with_fds (const gchar
*working_directory
,
837 GSpawnChildSetupFunc child_setup
,
845 g_return_val_if_fail (argv
!= NULL
, FALSE
);
846 g_return_val_if_fail (stdout_fd
< 0 ||
847 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
848 g_return_val_if_fail (stderr_fd
< 0 ||
849 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
850 /* can't inherit stdin if we have an input pipe. */
851 g_return_val_if_fail (stdin_fd
< 0 ||
852 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
854 return fork_exec_with_fds (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
858 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
859 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
860 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
861 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
862 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
863 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
864 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
865 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
877 * g_spawn_command_line_sync:
878 * @command_line: (type filename): a command line
879 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
880 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
881 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
882 * @error: return location for errors
884 * A simple version of g_spawn_sync() with little-used parameters
885 * removed, taking a command line instead of an argument vector. See
886 * g_spawn_sync() for full details. @command_line will be parsed by
887 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
888 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
889 * implications, so consider using g_spawn_sync() directly if
890 * appropriate. Possible errors are those from g_spawn_sync() and those
891 * from g_shell_parse_argv().
893 * If @exit_status is non-%NULL, the platform-specific exit status of
894 * the child is stored there; see the documentation of
895 * g_spawn_check_exit_status() for how to use and interpret this.
897 * On Windows, please note the implications of g_shell_parse_argv()
898 * parsing @command_line. Parsing is done according to Unix shell rules, not
899 * Windows command interpreter rules.
900 * Space is a separator, and backslashes are
901 * special. Thus you cannot simply pass a @command_line containing
902 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
903 * the backslashes will be eaten, and the space will act as a
904 * separator. You need to enclose such paths with single quotes, like
905 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
907 * Returns: %TRUE on success, %FALSE if an error was set
910 g_spawn_command_line_sync (const gchar
*command_line
,
911 gchar
**standard_output
,
912 gchar
**standard_error
,
919 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
921 if (!g_shell_parse_argv (command_line
,
926 retval
= g_spawn_sync (NULL
,
942 * g_spawn_command_line_async:
943 * @command_line: (type filename): a command line
944 * @error: return location for errors
946 * A simple version of g_spawn_async() that parses a command line with
947 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
948 * command line in the background. Unlike g_spawn_async(), the
949 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
950 * that %G_SPAWN_SEARCH_PATH can have security implications, so
951 * consider using g_spawn_async() directly if appropriate. Possible
952 * errors are those from g_shell_parse_argv() and g_spawn_async().
954 * The same concerns on Windows apply as for g_spawn_command_line_sync().
956 * Returns: %TRUE on success, %FALSE if error is set
959 g_spawn_command_line_async (const gchar
*command_line
,
965 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
967 if (!g_shell_parse_argv (command_line
,
972 retval
= g_spawn_async (NULL
,
986 * g_spawn_check_exit_status:
987 * @exit_status: An exit code as returned from g_spawn_sync()
990 * Set @error if @exit_status indicates the child exited abnormally
991 * (e.g. with a nonzero exit code, or via a fatal signal).
993 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
994 * exit status for subprocesses encoded in a platform-specific way.
995 * On Unix, this is guaranteed to be in the same format waitpid() returns,
996 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
998 * Prior to the introduction of this function in GLib 2.34, interpreting
999 * @exit_status required use of platform-specific APIs, which is problematic
1000 * for software using GLib as a cross-platform layer.
1002 * Additionally, many programs simply want to determine whether or not
1003 * the child exited successfully, and either propagate a #GError or
1004 * print a message to standard error. In that common case, this function
1005 * can be used. Note that the error message in @error will contain
1006 * human-readable information about the exit status.
1008 * The @domain and @code of @error have special semantics in the case
1009 * where the process has an "exit code", as opposed to being killed by
1010 * a signal. On Unix, this happens if WIFEXITED() would be true of
1011 * @exit_status. On Windows, it is always the case.
1013 * The special semantics are that the actual exit code will be the
1014 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1015 * This allows you to differentiate between different exit codes.
1017 * If the process was terminated by some means other than an exit
1018 * status, the domain will be %G_SPAWN_ERROR, and the code will be
1019 * %G_SPAWN_ERROR_FAILED.
1021 * This function just offers convenience; you can of course also check
1022 * the available platform via a macro such as %G_OS_UNIX, and use
1023 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
1024 * to scan or parse the error message string; it may be translated and/or
1025 * change in future versions of GLib.
1027 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1028 * @error will be set)
1033 g_spawn_check_exit_status (gint exit_status
,
1036 gboolean ret
= FALSE
;
1038 if (WIFEXITED (exit_status
))
1040 if (WEXITSTATUS (exit_status
) != 0)
1042 g_set_error (error
, G_SPAWN_EXIT_ERROR
, WEXITSTATUS (exit_status
),
1043 _("Child process exited with code %ld"),
1044 (long) WEXITSTATUS (exit_status
));
1048 else if (WIFSIGNALED (exit_status
))
1050 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
1051 _("Child process killed by signal %ld"),
1052 (long) WTERMSIG (exit_status
));
1055 else if (WIFSTOPPED (exit_status
))
1057 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
1058 _("Child process stopped by signal %ld"),
1059 (long) WSTOPSIG (exit_status
));
1064 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
1065 _("Child process exited abnormally"));
1075 write_all (gint fd
, gconstpointer vbuf
, gsize to_write
)
1077 gchar
*buf
= (gchar
*) vbuf
;
1079 while (to_write
> 0)
1081 gssize count
= write (fd
, buf
, to_write
);
1099 write_err_and_exit (gint fd
, gint msg
)
1103 write_all (fd
, &msg
, sizeof(msg
));
1104 write_all (fd
, &en
, sizeof(en
));
1110 set_cloexec (void *data
, gint fd
)
1112 if (fd
>= GPOINTER_TO_INT (data
))
1113 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
1120 fdwalk (int (*cb
)(void *data
, int fd
), void *data
)
1126 #ifdef HAVE_SYS_RESOURCE_H
1133 if ((d
= opendir("/proc/self/fd"))) {
1136 while ((de
= readdir(d
))) {
1140 if (de
->d_name
[0] == '.')
1144 l
= strtol(de
->d_name
, &e
, 10);
1145 if (errno
!= 0 || !e
|| *e
)
1150 if ((glong
) fd
!= l
)
1156 if ((res
= cb (data
, fd
)) != 0)
1164 /* If /proc is not mounted or not accessible we fall back to the old
1169 #ifdef HAVE_SYS_RESOURCE_H
1171 if (getrlimit(RLIMIT_NOFILE
, &rl
) == 0 && rl
.rlim_max
!= RLIM_INFINITY
)
1172 open_max
= rl
.rlim_max
;
1175 open_max
= sysconf (_SC_OPEN_MAX
);
1177 for (fd
= 0; fd
< open_max
; fd
++)
1178 if ((res
= cb (data
, fd
)) != 0)
1186 sane_dup2 (gint fd1
, gint fd2
)
1191 ret
= dup2 (fd1
, fd2
);
1192 if (ret
< 0 && errno
== EINTR
)
1199 sane_open (const char *path
, gint mode
)
1204 ret
= open (path
, mode
);
1205 if (ret
< 0 && errno
== EINTR
)
1220 do_exec (gint child_err_report_fd
,
1224 const gchar
*working_directory
,
1227 gboolean close_descriptors
,
1228 gboolean search_path
,
1229 gboolean search_path_from_envp
,
1230 gboolean stdout_to_null
,
1231 gboolean stderr_to_null
,
1232 gboolean child_inherits_stdin
,
1233 gboolean file_and_argv_zero
,
1234 GSpawnChildSetupFunc child_setup
,
1237 if (working_directory
&& chdir (working_directory
) < 0)
1238 write_err_and_exit (child_err_report_fd
,
1239 CHILD_CHDIR_FAILED
);
1241 /* Close all file descriptors but stdin stdout and stderr as
1242 * soon as we exec. Note that this includes
1243 * child_err_report_fd, which keeps the parent from blocking
1244 * forever on the other end of that pipe.
1246 if (close_descriptors
)
1248 fdwalk (set_cloexec
, GINT_TO_POINTER(3));
1252 /* We need to do child_err_report_fd anyway */
1253 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd
);
1256 /* Redirect pipes as required */
1260 /* dup2 can't actually fail here I don't think */
1262 if (sane_dup2 (stdin_fd
, 0) < 0)
1263 write_err_and_exit (child_err_report_fd
,
1266 set_cloexec (GINT_TO_POINTER(0), stdin_fd
);
1268 else if (!child_inherits_stdin
)
1270 /* Keep process from blocking on a read of stdin */
1271 gint read_null
= sane_open ("/dev/null", O_RDONLY
);
1272 g_assert (read_null
!= -1);
1273 sane_dup2 (read_null
, 0);
1274 close_and_invalidate (&read_null
);
1279 /* dup2 can't actually fail here I don't think */
1281 if (sane_dup2 (stdout_fd
, 1) < 0)
1282 write_err_and_exit (child_err_report_fd
,
1285 set_cloexec (GINT_TO_POINTER(0), stdout_fd
);
1287 else if (stdout_to_null
)
1289 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1290 g_assert (write_null
!= -1);
1291 sane_dup2 (write_null
, 1);
1292 close_and_invalidate (&write_null
);
1297 /* dup2 can't actually fail here I don't think */
1299 if (sane_dup2 (stderr_fd
, 2) < 0)
1300 write_err_and_exit (child_err_report_fd
,
1303 set_cloexec (GINT_TO_POINTER(0), stderr_fd
);
1305 else if (stderr_to_null
)
1307 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1308 sane_dup2 (write_null
, 2);
1309 close_and_invalidate (&write_null
);
1312 /* Call user function just before we exec */
1315 (* child_setup
) (user_data
);
1319 file_and_argv_zero
? argv
+ 1 : argv
,
1320 envp
, search_path
, search_path_from_envp
);
1323 write_err_and_exit (child_err_report_fd
,
1340 if (bytes
>= sizeof(gint
)*2)
1341 break; /* give up, who knows what happened, should not be
1347 ((gchar
*)buf
) + bytes
,
1348 sizeof(gint
) * n_ints_in_buf
- bytes
);
1349 if (chunk
< 0 && errno
== EINTR
)
1356 /* Some weird shit happened, bail out */
1359 G_SPAWN_ERROR_FAILED
,
1360 _("Failed to read from child pipe (%s)"),
1361 g_strerror (errsv
));
1365 else if (chunk
== 0)
1367 else /* chunk > 0 */
1371 *n_ints_read
= (gint
)(bytes
/ sizeof(gint
));
1376 #ifdef POSIX_SPAWN_AVAILABLE
1378 do_posix_spawn (gchar
**argv
,
1380 gboolean search_path
,
1381 gboolean stdout_to_null
,
1382 gboolean stderr_to_null
,
1383 gboolean child_inherits_stdin
,
1384 gboolean file_and_argv_zero
,
1386 gint
*child_close_fds
,
1393 posix_spawnattr_t attr
;
1394 posix_spawn_file_actions_t file_actions
;
1395 gint parent_close_fds
[3];
1396 gint num_parent_close_fds
= 0;
1397 GSList
*child_close
= NULL
;
1402 if (*argv
[0] == '\0')
1404 /* We check the simple case first. */
1408 r
= posix_spawnattr_init (&attr
);
1412 if (child_close_fds
)
1415 while (child_close_fds
[++i
] != -1)
1416 child_close
= g_slist_prepend (child_close
,
1417 GINT_TO_POINTER (child_close_fds
[i
]));
1420 r
= posix_spawnattr_setflags (&attr
, POSIX_SPAWN_SETSIGDEF
);
1422 goto out_free_spawnattr
;
1424 /* Reset some signal handlers that we may use */
1425 sigemptyset (&mask
);
1426 sigaddset (&mask
, SIGCHLD
);
1427 sigaddset (&mask
, SIGINT
);
1428 sigaddset (&mask
, SIGTERM
);
1429 sigaddset (&mask
, SIGHUP
);
1431 r
= posix_spawnattr_setsigdefault (&attr
, &mask
);
1433 goto out_free_spawnattr
;
1435 r
= posix_spawn_file_actions_init (&file_actions
);
1437 goto out_free_spawnattr
;
1439 /* Redirect pipes as required */
1443 r
= posix_spawn_file_actions_adddup2 (&file_actions
, stdin_fd
, 0);
1447 if (!g_slist_find (child_close
, GINT_TO_POINTER (stdin_fd
)))
1448 child_close
= g_slist_prepend (child_close
, GINT_TO_POINTER (stdin_fd
));
1450 else if (!child_inherits_stdin
)
1452 /* Keep process from blocking on a read of stdin */
1453 gint read_null
= sane_open ("/dev/null", O_RDONLY
| O_CLOEXEC
);
1454 g_assert (read_null
!= -1);
1455 parent_close_fds
[num_parent_close_fds
++] = read_null
;
1457 r
= posix_spawn_file_actions_adddup2 (&file_actions
, read_null
, 0);
1464 r
= posix_spawn_file_actions_adddup2 (&file_actions
, stdout_fd
, 1);
1468 if (!g_slist_find (child_close
, GINT_TO_POINTER (stdout_fd
)))
1469 child_close
= g_slist_prepend (child_close
, GINT_TO_POINTER (stdout_fd
));
1471 else if (stdout_to_null
)
1473 gint write_null
= sane_open ("/dev/null", O_WRONLY
| O_CLOEXEC
);
1474 g_assert (write_null
!= -1);
1475 parent_close_fds
[num_parent_close_fds
++] = write_null
;
1477 r
= posix_spawn_file_actions_adddup2 (&file_actions
, write_null
, 1);
1484 r
= posix_spawn_file_actions_adddup2 (&file_actions
, stderr_fd
, 2);
1488 if (!g_slist_find (child_close
, GINT_TO_POINTER (stderr_fd
)))
1489 child_close
= g_slist_prepend (child_close
, GINT_TO_POINTER (stderr_fd
));
1491 else if (stderr_to_null
)
1493 gint write_null
= sane_open ("/dev/null", O_WRONLY
| O_CLOEXEC
);
1494 g_assert (write_null
!= -1);
1495 parent_close_fds
[num_parent_close_fds
++] = write_null
;
1497 r
= posix_spawn_file_actions_adddup2 (&file_actions
, write_null
, 2);
1502 /* Intentionally close the fds in the child as the last file action,
1503 * having been careful not to add the same fd to this list twice.
1505 * This is important to allow (e.g.) for the same fd to be passed as stdout
1506 * and stderr (we must not close it before we have dupped it in both places,
1507 * and we must not attempt to close it twice).
1509 for (elem
= child_close
; elem
!= NULL
; elem
= elem
->next
)
1511 r
= posix_spawn_file_actions_addclose (&file_actions
,
1512 GPOINTER_TO_INT (elem
->data
));
1517 argv_pass
= file_and_argv_zero
? argv
+ 1 : argv
;
1521 /* Don't search when it contains a slash. */
1522 if (!search_path
|| strchr (argv
[0], '/') != NULL
)
1523 r
= posix_spawn (&pid
, argv
[0], &file_actions
, &attr
, argv_pass
, envp
);
1525 r
= posix_spawnp (&pid
, argv
[0], &file_actions
, &attr
, argv_pass
, envp
);
1527 if (r
== 0 && child_pid
!= NULL
)
1531 for (i
= 0; i
< num_parent_close_fds
; i
++)
1532 close_and_invalidate (&parent_close_fds
[i
]);
1534 posix_spawn_file_actions_destroy (&file_actions
);
1536 posix_spawnattr_destroy (&attr
);
1537 g_slist_free (child_close
);
1541 #endif /* POSIX_SPAWN_AVAILABLE */
1544 fork_exec_with_fds (gboolean intermediate_child
,
1545 const gchar
*working_directory
,
1548 gboolean close_descriptors
,
1549 gboolean search_path
,
1550 gboolean search_path_from_envp
,
1551 gboolean stdout_to_null
,
1552 gboolean stderr_to_null
,
1553 gboolean child_inherits_stdin
,
1554 gboolean file_and_argv_zero
,
1555 gboolean cloexec_pipes
,
1556 GSpawnChildSetupFunc child_setup
,
1559 gint
*child_close_fds
,
1566 gint child_err_report_pipe
[2] = { -1, -1 };
1567 gint child_pid_report_pipe
[2] = { -1, -1 };
1568 guint pipe_flags
= cloexec_pipes
? FD_CLOEXEC
: 0;
1571 #ifdef POSIX_SPAWN_AVAILABLE
1572 if (!intermediate_child
&& working_directory
== NULL
&& !close_descriptors
&&
1573 !search_path_from_envp
&& child_setup
== NULL
)
1575 g_debug ("Launching with posix_spawn");
1576 status
= do_posix_spawn (argv
,
1581 child_inherits_stdin
,
1591 if (status
!= ENOEXEC
)
1595 G_SPAWN_ERROR_FAILED
,
1596 _("Failed to spawn child process “%s” (%s)"),
1598 g_strerror (status
));
1602 /* posix_spawn is not intended to support script execution. It does in
1603 * some situations on some glibc versions, but that will be fixed.
1604 * So if it fails with ENOEXEC, we fall through to the regular
1605 * gspawn codepath so that script execution can be attempted,
1606 * per standard gspawn behaviour. */
1607 g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
1611 g_debug ("posix_spawn avoided %s%s%s%s%s",
1612 !intermediate_child
? "" : "(automatic reaping requested) ",
1613 working_directory
== NULL
? "" : "(workdir specified) ",
1614 !close_descriptors
? "" : "(fd close requested) ",
1615 !search_path_from_envp
? "" : "(using envp for search path) ",
1616 child_setup
== NULL
? "" : "(child_setup specified) ");
1618 #endif /* POSIX_SPAWN_AVAILABLE */
1620 if (!g_unix_open_pipe (child_err_report_pipe
, pipe_flags
, error
))
1623 if (intermediate_child
&& !g_unix_open_pipe (child_pid_report_pipe
, pipe_flags
, error
))
1624 goto cleanup_and_fail
;
1635 _("Failed to fork (%s)"),
1636 g_strerror (errsv
));
1638 goto cleanup_and_fail
;
1642 /* Immediate child. This may or may not be the child that
1643 * actually execs the new process.
1646 /* Reset some signal handlers that we may use */
1647 signal (SIGCHLD
, SIG_DFL
);
1648 signal (SIGINT
, SIG_DFL
);
1649 signal (SIGTERM
, SIG_DFL
);
1650 signal (SIGHUP
, SIG_DFL
);
1652 /* Be sure we crash if the parent exits
1653 * and we write to the err_report_pipe
1655 signal (SIGPIPE
, SIG_DFL
);
1657 /* Close the parent's end of the pipes;
1658 * not needed in the close_descriptors case,
1661 close_and_invalidate (&child_err_report_pipe
[0]);
1662 close_and_invalidate (&child_pid_report_pipe
[0]);
1663 if (child_close_fds
!= NULL
)
1666 while (child_close_fds
[++i
] != -1)
1667 close_and_invalidate (&child_close_fds
[i
]);
1670 if (intermediate_child
)
1672 /* We need to fork an intermediate child that launches the
1673 * final child. The purpose of the intermediate child
1674 * is to exit, so we can waitpid() it immediately.
1675 * Then the grandchild will not become a zombie.
1677 GPid grandchild_pid
;
1679 grandchild_pid
= fork ();
1681 if (grandchild_pid
< 0)
1683 /* report -1 as child PID */
1684 write_all (child_pid_report_pipe
[1], &grandchild_pid
,
1685 sizeof(grandchild_pid
));
1687 write_err_and_exit (child_err_report_pipe
[1],
1690 else if (grandchild_pid
== 0)
1692 close_and_invalidate (&child_pid_report_pipe
[1]);
1693 do_exec (child_err_report_pipe
[1],
1702 search_path_from_envp
,
1705 child_inherits_stdin
,
1712 write_all (child_pid_report_pipe
[1], &grandchild_pid
, sizeof(grandchild_pid
));
1713 close_and_invalidate (&child_pid_report_pipe
[1]);
1720 /* Just run the child.
1723 do_exec (child_err_report_pipe
[1],
1732 search_path_from_envp
,
1735 child_inherits_stdin
,
1748 /* Close the uncared-about ends of the pipes */
1749 close_and_invalidate (&child_err_report_pipe
[1]);
1750 close_and_invalidate (&child_pid_report_pipe
[1]);
1752 /* If we had an intermediate child, reap it */
1753 if (intermediate_child
)
1756 if (waitpid (pid
, &status
, 0) < 0)
1760 else if (errno
== ECHILD
)
1761 ; /* do nothing, child already reaped */
1763 g_warning ("waitpid() should not fail in "
1764 "'fork_exec_with_pipes'");
1769 if (!read_ints (child_err_report_pipe
[0],
1772 goto cleanup_and_fail
;
1776 /* Error from the child. */
1780 case CHILD_CHDIR_FAILED
:
1783 G_SPAWN_ERROR_CHDIR
,
1784 _("Failed to change to directory “%s” (%s)"),
1786 g_strerror (buf
[1]));
1790 case CHILD_EXEC_FAILED
:
1793 _g_spawn_exec_err_to_g_error (buf
[1]),
1794 _("Failed to execute child process “%s” (%s)"),
1796 g_strerror (buf
[1]));
1800 case CHILD_DUP2_FAILED
:
1803 G_SPAWN_ERROR_FAILED
,
1804 _("Failed to redirect output or input of child process (%s)"),
1805 g_strerror (buf
[1]));
1809 case CHILD_FORK_FAILED
:
1813 _("Failed to fork child process (%s)"),
1814 g_strerror (buf
[1]));
1820 G_SPAWN_ERROR_FAILED
,
1821 _("Unknown error executing child process “%s”"),
1826 goto cleanup_and_fail
;
1829 /* Get child pid from intermediate child pipe. */
1830 if (intermediate_child
)
1834 if (!read_ints (child_pid_report_pipe
[0],
1835 buf
, 1, &n_ints
, error
))
1836 goto cleanup_and_fail
;
1844 G_SPAWN_ERROR_FAILED
,
1845 _("Failed to read enough data from child pid pipe (%s)"),
1846 g_strerror (errsv
));
1847 goto cleanup_and_fail
;
1851 /* we have the child pid */
1856 /* Success against all odds! return the information */
1857 close_and_invalidate (&child_err_report_pipe
[0]);
1858 close_and_invalidate (&child_pid_report_pipe
[0]);
1868 /* There was an error from the Child, reap the child to avoid it being
1875 if (waitpid (pid
, NULL
, 0) < 0)
1879 else if (errno
== ECHILD
)
1880 ; /* do nothing, child already reaped */
1882 g_warning ("waitpid() should not fail in "
1883 "'fork_exec_with_pipes'");
1887 close_and_invalidate (&child_err_report_pipe
[0]);
1888 close_and_invalidate (&child_err_report_pipe
[1]);
1889 close_and_invalidate (&child_pid_report_pipe
[0]);
1890 close_and_invalidate (&child_pid_report_pipe
[1]);
1896 fork_exec_with_pipes (gboolean intermediate_child
,
1897 const gchar
*working_directory
,
1900 gboolean close_descriptors
,
1901 gboolean search_path
,
1902 gboolean search_path_from_envp
,
1903 gboolean stdout_to_null
,
1904 gboolean stderr_to_null
,
1905 gboolean child_inherits_stdin
,
1906 gboolean file_and_argv_zero
,
1907 gboolean cloexec_pipes
,
1908 GSpawnChildSetupFunc child_setup
,
1911 gint
*standard_input
,
1912 gint
*standard_output
,
1913 gint
*standard_error
,
1916 guint pipe_flags
= cloexec_pipes
? FD_CLOEXEC
: 0;
1917 gint stdin_pipe
[2] = { -1, -1 };
1918 gint stdout_pipe
[2] = { -1, -1 };
1919 gint stderr_pipe
[2] = { -1, -1 };
1920 gint child_close_fds
[4];
1923 if (standard_input
&& !g_unix_open_pipe (stdin_pipe
, pipe_flags
, error
))
1924 goto cleanup_and_fail
;
1926 if (standard_output
&& !g_unix_open_pipe (stdout_pipe
, pipe_flags
, error
))
1927 goto cleanup_and_fail
;
1929 if (standard_error
&& !g_unix_open_pipe (stderr_pipe
, FD_CLOEXEC
, error
))
1930 goto cleanup_and_fail
;
1932 child_close_fds
[0] = stdin_pipe
[1];
1933 child_close_fds
[1] = stdout_pipe
[0];
1934 child_close_fds
[2] = stderr_pipe
[0];
1935 child_close_fds
[3] = -1;
1937 ret
= fork_exec_with_fds (intermediate_child
,
1943 search_path_from_envp
,
1946 child_inherits_stdin
,
1958 goto cleanup_and_fail
;
1960 /* Close the uncared-about ends of the pipes */
1961 close_and_invalidate (&stdin_pipe
[0]);
1962 close_and_invalidate (&stdout_pipe
[1]);
1963 close_and_invalidate (&stderr_pipe
[1]);
1966 *standard_input
= stdin_pipe
[1];
1968 if (standard_output
)
1969 *standard_output
= stdout_pipe
[0];
1972 *standard_error
= stderr_pipe
[0];
1977 close_and_invalidate (&stdin_pipe
[0]);
1978 close_and_invalidate (&stdin_pipe
[1]);
1979 close_and_invalidate (&stdout_pipe
[0]);
1980 close_and_invalidate (&stdout_pipe
[1]);
1981 close_and_invalidate (&stderr_pipe
[0]);
1982 close_and_invalidate (&stderr_pipe
[1]);
1987 /* Based on execvp from GNU C Library */
1990 script_execute (const gchar
*file
,
1994 /* Count the arguments. */
1999 /* Construct an argument list for the shell. */
2003 new_argv
= g_new0 (gchar
*, argc
+ 2); /* /bin/sh and NULL */
2005 new_argv
[0] = (char *) "/bin/sh";
2006 new_argv
[1] = (char *) file
;
2009 new_argv
[argc
+ 1] = argv
[argc
];
2013 /* Execute the shell. */
2015 execve (new_argv
[0], new_argv
, envp
);
2017 execv (new_argv
[0], new_argv
);
2024 my_strchrnul (const gchar
*str
, gchar c
)
2026 gchar
*p
= (gchar
*) str
;
2027 while (*p
&& (*p
!= c
))
2034 g_execute (const gchar
*file
,
2037 gboolean search_path
,
2038 gboolean search_path_from_envp
)
2042 /* We check the simple case first. */
2047 if (!(search_path
|| search_path_from_envp
) || strchr (file
, '/') != NULL
)
2049 /* Don't search when it contains a slash. */
2051 execve (file
, argv
, envp
);
2055 if (errno
== ENOEXEC
)
2056 script_execute (file
, argv
, envp
);
2060 gboolean got_eacces
= 0;
2061 const gchar
*path
, *p
;
2062 gchar
*name
, *freeme
;
2067 if (search_path_from_envp
)
2068 path
= g_environ_getenv (envp
, "PATH");
2069 if (search_path
&& path
== NULL
)
2070 path
= g_getenv ("PATH");
2074 /* There is no 'PATH' in the environment. The default
2075 * search path in libc is the current directory followed by
2076 * the path 'confstr' returns for '_CS_PATH'.
2079 /* In GLib we put . last, for security, and don't use the
2080 * unportable confstr(); UNIX98 does not actually specify
2081 * what to search if PATH is unset. POSIX may, dunno.
2084 path
= "/bin:/usr/bin:.";
2087 len
= strlen (file
) + 1;
2088 pathlen
= strlen (path
);
2089 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
2091 /* Copy the file name at the top, including '\0' */
2092 memcpy (name
+ pathlen
+ 1, file
, len
);
2093 name
= name
+ pathlen
;
2094 /* And add the slash before the filename */
2103 p
= my_strchrnul (path
, ':');
2106 /* Two adjacent colons, or a colon at the beginning or the end
2107 * of 'PATH' means to search the current directory.
2111 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
2113 /* Try to execute this name. If it works, execv will not return. */
2115 execve (startp
, argv
, envp
);
2117 execv (startp
, argv
);
2119 if (errno
== ENOEXEC
)
2120 script_execute (startp
, argv
, envp
);
2125 /* Record the we got a 'Permission denied' error. If we end
2126 * up finding no executable we can use, we want to diagnose
2127 * that we did find one but were denied access.
2140 /* Those errors indicate the file is missing or not executable
2141 * by us, in which case we want to just try the next path
2148 /* Some strange filesystems like AFS return even
2149 * stranger error numbers. They cannot reasonably mean anything
2150 * else so ignore those, too.
2155 /* Some other error means we found an executable file, but
2156 * something went wrong executing it; return the error to our
2163 while (*p
++ != '\0');
2165 /* We tried every element and none of them worked. */
2167 /* At least one failure was due to permissions, so report that
2175 /* Return the error from the last attempt (probably ENOENT). */
2180 * g_spawn_close_pid:
2181 * @pid: The process reference to close
2183 * On some platforms, notably Windows, the #GPid type represents a resource
2184 * which must be closed to prevent resource leaking. g_spawn_close_pid()
2185 * is provided for this purpose. It should be used on all platforms, even
2186 * though it doesn't do anything under UNIX.
2189 g_spawn_close_pid (GPid pid
)