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 * GLib is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * GLib 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
18 * License along with GLib; see the file COPYING.LIB. If not, write
19 * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
26 #include <sys/types.h>
33 #include <stdlib.h> /* for fdwalk */
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
46 #include "glib/gstdio.h"
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
56 #include "glib-unix.h"
60 * @Short_description: process launching
61 * @Title: Spawning Processes
63 * GLib supports spawning of processes with an API that is more
64 * convenient than the bare UNIX fork() and exec().
66 * The g_spawn family of functions has synchronous (g_spawn_sync())
67 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
68 * as well as convenience variants that take a complete shell-like
69 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
71 * See #GSubprocess in GIO for a higher-level API that provides
72 * stream interfaces for communication with child processes.
77 static gint
g_execute (const gchar
*file
,
81 gboolean search_path_from_envp
);
83 static gboolean
fork_exec_with_pipes (gboolean intermediate_child
,
84 const gchar
*working_directory
,
87 gboolean close_descriptors
,
89 gboolean search_path_from_envp
,
90 gboolean stdout_to_null
,
91 gboolean stderr_to_null
,
92 gboolean child_inherits_stdin
,
93 gboolean file_and_argv_zero
,
94 gboolean cloexec_pipes
,
95 GSpawnChildSetupFunc child_setup
,
99 gint
*standard_output
,
100 gint
*standard_error
,
103 G_DEFINE_QUARK (g
-exec
-error
-quark
, g_spawn_error
)
104 G_DEFINE_QUARK (g
-spawn
-exit
-error
-quark
, g_spawn_exit_error
)
108 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
109 * @argv: (array zero-terminated=1): child's argument vector
110 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
111 * @flags: flags from #GSpawnFlags
112 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
113 * @user_data: (closure): user data for @child_setup
114 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
115 * @error: return location for error
117 * See g_spawn_async_with_pipes() for a full description; this function
118 * simply calls the g_spawn_async_with_pipes() without any pipes.
120 * You should call g_spawn_close_pid() on the returned child process
121 * reference when you don't need it any more.
123 * If you are writing a GTK+ application, and the program you are
124 * spawning is a graphical application, too, then you may want to
125 * use gdk_spawn_on_screen() instead to ensure that the spawned program
126 * opens its windows on the right screen.
128 * Note that the returned @child_pid on Windows is a handle to the child
129 * process and not its identifier. Process handles and process identifiers
130 * are different concepts on Windows.
132 * Returns: %TRUE on success, %FALSE if error is set
135 g_spawn_async (const gchar
*working_directory
,
139 GSpawnChildSetupFunc child_setup
,
144 g_return_val_if_fail (argv
!= NULL
, FALSE
);
146 return g_spawn_async_with_pipes (working_directory
,
156 /* Avoids a danger in threaded situations (calling close()
157 * on a file descriptor twice, and another thread has
158 * re-opened it since the first close)
161 close_and_invalidate (gint
*fd
)
167 (void) g_close (*fd
, NULL
);
172 /* Some versions of OS X define READ_OK in public headers */
177 READ_FAILED
= 0, /* FALSE */
183 read_data (GString
*str
,
191 bytes
= read (fd
, buf
, 4096);
197 g_string_append_len (str
, buf
, bytes
);
200 else if (errno
== EINTR
)
209 _("Failed to read data from child process (%s)"),
218 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
219 * @argv: (array zero-terminated=1): child's argument vector
220 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
221 * @flags: flags from #GSpawnFlags
222 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
223 * @user_data: (closure): user data for @child_setup
224 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
225 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
226 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
227 * @error: return location for error, or %NULL
229 * Executes a child synchronously (waits for the child to exit before returning).
230 * All output from the child is stored in @standard_output and @standard_error,
231 * if those parameters are non-%NULL. Note that you must set the
232 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
233 * passing %NULL for @standard_output and @standard_error.
235 * If @exit_status is non-%NULL, the platform-specific exit status of
236 * the child is stored there; see the documentation of
237 * g_spawn_check_exit_status() for how to use and interpret this.
238 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
241 * If an error occurs, no data is returned in @standard_output,
242 * @standard_error, or @exit_status.
244 * This function calls g_spawn_async_with_pipes() internally; see that
245 * function for full details on the other parameters and details on
246 * how these functions work on Windows.
248 * Returns: %TRUE on success, %FALSE if an error was set
251 g_spawn_sync (const gchar
*working_directory
,
255 GSpawnChildSetupFunc child_setup
,
257 gchar
**standard_output
,
258 gchar
**standard_error
,
267 GString
*outstr
= NULL
;
268 GString
*errstr
= NULL
;
272 g_return_val_if_fail (argv
!= NULL
, FALSE
);
273 g_return_val_if_fail (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
), FALSE
);
274 g_return_val_if_fail (standard_output
== NULL
||
275 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
276 g_return_val_if_fail (standard_error
== NULL
||
277 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
279 /* Just to ensure segfaults if callers try to use
280 * these when an error is reported.
283 *standard_output
= NULL
;
286 *standard_error
= NULL
;
288 if (!fork_exec_with_pipes (FALSE
,
292 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
293 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
294 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
295 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
296 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
297 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
298 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
299 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
304 standard_output
? &outpipe
: NULL
,
305 standard_error
? &errpipe
: NULL
,
309 /* Read data from child. */
315 outstr
= g_string_new (NULL
);
320 errstr
= g_string_new (NULL
);
323 /* Read data until we get EOF on both pipes. */
332 FD_SET (outpipe
, &fds
);
334 FD_SET (errpipe
, &fds
);
336 ret
= select (MAX (outpipe
, errpipe
) + 1,
339 NULL
/* no timeout */);
353 _("Unexpected error in select() reading data from a child process (%s)"),
359 if (outpipe
>= 0 && FD_ISSET (outpipe
, &fds
))
361 switch (read_data (outstr
, outpipe
, error
))
367 close_and_invalidate (&outpipe
);
378 if (errpipe
>= 0 && FD_ISSET (errpipe
, &fds
))
380 switch (read_data (errstr
, errpipe
, error
))
386 close_and_invalidate (&errpipe
);
398 /* These should only be open still if we had an error. */
401 close_and_invalidate (&outpipe
);
403 close_and_invalidate (&errpipe
);
405 /* Wait for child to exit, even if we have
410 ret
= waitpid (pid
, &status
, 0);
416 else if (errno
== ECHILD
)
420 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_spawn_sync either directly or indirectly.");
424 /* We don't need the exit status. */
429 if (!failed
) /* avoid error pileups */
438 _("Unexpected error in waitpid() (%s)"),
447 g_string_free (outstr
, TRUE
);
449 g_string_free (errstr
, TRUE
);
456 *exit_status
= status
;
459 *standard_output
= g_string_free (outstr
, FALSE
);
462 *standard_error
= g_string_free (errstr
, FALSE
);
469 * g_spawn_async_with_pipes:
470 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
471 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
472 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
473 * @flags: flags from #GSpawnFlags
474 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
475 * @user_data: (closure): user data for @child_setup
476 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
477 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
478 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
479 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
480 * @error: return location for error
482 * Executes a child program asynchronously (your program will not
483 * block waiting for the child to exit). The child program is
484 * specified by the only argument that must be provided, @argv.
485 * @argv should be a %NULL-terminated array of strings, to be passed
486 * as the argument vector for the child. The first string in @argv
487 * is of course the name of the program to execute. By default, the
488 * name of the program must be a full path. If @flags contains the
489 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
490 * used to search for the executable. If @flags contains the
491 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
492 * @envp is used to search for the executable. If both the
493 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
494 * are set, the `PATH` variable from @envp takes precedence over
495 * the environment variable.
497 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
498 * used, then the program will be run from the current directory (or
499 * @working_directory, if specified); this might be unexpected or even
500 * dangerous in some cases when the current directory is world-writable.
502 * On Windows, note that all the string or string vector arguments to
503 * this function and the other g_spawn*() functions are in UTF-8, the
504 * GLib file name encoding. Unicode characters that are not part of
505 * the system codepage passed in these arguments will be correctly
506 * available in the spawned program only if it uses wide character API
507 * to retrieve its command line. For C programs built with Microsoft's
508 * tools it is enough to make the program have a wmain() instead of
509 * main(). wmain() has a wide character argument vector as parameter.
511 * At least currently, mingw doesn't support wmain(), so if you use
512 * mingw to develop the spawned program, it will have to call the
513 * undocumented function __wgetmainargs() to get the wide character
514 * argument vector and environment. See gspawn-win32-helper.c in the
515 * GLib sources or init.c in the mingw runtime sources for a prototype
516 * for that function. Alternatively, you can retrieve the Win32 system
517 * level wide character command line passed to the spawned program
518 * using the GetCommandLineW() function.
520 * On Windows the low-level child process creation API CreateProcess()
521 * doesn't use argument vectors, but a command line. The C runtime
522 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
523 * eventually calls) paste the argument vector elements together into
524 * a command line, and the C runtime startup code does a corresponding
525 * reconstruction of an argument vector from the command line, to be
526 * passed to main(). Complications arise when you have argument vector
527 * elements that contain spaces of double quotes. The spawn*() functions
528 * don't do any quoting or escaping, but on the other hand the startup
529 * code does do unquoting and unescaping in order to enable receiving
530 * arguments with embedded spaces or double quotes. To work around this
531 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
532 * argument vector elements that need it before calling the C runtime
535 * The returned @child_pid on Windows is a handle to the child
536 * process, not its identifier. Process handles and process
537 * identifiers are different concepts on Windows.
539 * @envp is a %NULL-terminated array of strings, where each string
540 * has the form `KEY=VALUE`. This will become the child's environment.
541 * If @envp is %NULL, the child inherits its parent's environment.
543 * @flags should be the bitwise OR of any flags you want to affect the
544 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
545 * child will not automatically be reaped; you must use a child watch to
546 * be notified about the death of the child process. Eventually you must
547 * call g_spawn_close_pid() on the @child_pid, in order to free
548 * resources which may be associated with the child process. (On Unix,
549 * using a child watch is equivalent to calling waitpid() or handling
550 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
551 * is equivalent to calling CloseHandle() on the process handle returned
552 * in @child_pid). See g_child_watch_add().
554 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
555 * descriptors will be inherited by the child; otherwise all descriptors
556 * except stdin/stdout/stderr will be closed before calling exec() in
557 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
558 * absolute path, it will be looked for in the `PATH` environment
559 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
560 * absolute path, it will be looked for in the `PATH` variable from
561 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
562 * are used, the value from @envp takes precedence over the environment.
563 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
564 * will be discarded, instead of going to the same location as the parent's
565 * standard output. If you use this flag, @standard_output must be %NULL.
566 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
567 * will be discarded, instead of going to the same location as the parent's
568 * standard error. If you use this flag, @standard_error must be %NULL.
569 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
570 * standard input (by default, the child's standard input is attached to
571 * /dev/null). If you use this flag, @standard_input must be %NULL.
572 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
573 * the file to execute, while the remaining elements are the actual
574 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
575 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
577 * @child_setup and @user_data are a function and user data. On POSIX
578 * platforms, the function is called in the child after GLib has
579 * performed all the setup it plans to perform (including creating
580 * pipes, closing file descriptors, etc.) but before calling exec().
581 * That is, @child_setup is called just before calling exec() in the
582 * child. Obviously actions taken in this function will only affect
583 * the child, not the parent.
585 * On Windows, there is no separate fork() and exec() functionality.
586 * Child processes are created and run with a single API call,
587 * CreateProcess(). There is no sensible thing @child_setup
588 * could be used for on Windows so it is ignored and not called.
590 * If non-%NULL, @child_pid will on Unix be filled with the child's
591 * process ID. You can use the process ID to send signals to the child,
592 * or to use g_child_watch_add() (or waitpid()) if you specified the
593 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
594 * filled with a handle to the child process only if you specified the
595 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
596 * process using the Win32 API, for example wait for its termination
597 * with the WaitFor*() functions, or examine its exit code with
598 * GetExitCodeProcess(). You should close the handle with CloseHandle()
599 * or g_spawn_close_pid() when you no longer need it.
601 * If non-%NULL, the @standard_input, @standard_output, @standard_error
602 * locations will be filled with file descriptors for writing to the child's
603 * standard input or reading from its standard output or standard error.
604 * The caller of g_spawn_async_with_pipes() must close these file descriptors
605 * when they are no longer in use. If these parameters are %NULL, the
606 * corresponding pipe won't be created.
608 * If @standard_input is NULL, the child's standard input is attached to
609 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
611 * If @standard_error is NULL, the child's standard error goes to the same
612 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
615 * If @standard_output is NULL, the child's standard output goes to the same
616 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
619 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
620 * If an error is set, the function returns %FALSE. Errors are reported
621 * even if they occur in the child (for example if the executable in
622 * @argv[0] is not found). Typically the `message` field of returned
623 * errors should be displayed to users. Possible errors are those from
624 * the #G_SPAWN_ERROR domain.
626 * If an error occurs, @child_pid, @standard_input, @standard_output,
627 * and @standard_error will not be filled with valid values.
629 * If @child_pid is not %NULL and an error does not occur then the returned
630 * process reference must be closed using g_spawn_close_pid().
632 * If you are writing a GTK+ application, and the program you
633 * are spawning is a graphical application, too, then you may
634 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
635 * the spawned program opens its windows on the right screen.
637 * Returns: %TRUE on success, %FALSE if an error was set
640 g_spawn_async_with_pipes (const gchar
*working_directory
,
644 GSpawnChildSetupFunc child_setup
,
647 gint
*standard_input
,
648 gint
*standard_output
,
649 gint
*standard_error
,
652 g_return_val_if_fail (argv
!= NULL
, FALSE
);
653 g_return_val_if_fail (standard_output
== NULL
||
654 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
655 g_return_val_if_fail (standard_error
== NULL
||
656 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
657 /* can't inherit stdin if we have an input pipe. */
658 g_return_val_if_fail (standard_input
== NULL
||
659 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
661 return fork_exec_with_pipes (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
665 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
666 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
667 (flags
& G_SPAWN_SEARCH_PATH_FROM_ENVP
) != 0,
668 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
669 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
670 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
671 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
672 (flags
& G_SPAWN_CLOEXEC_PIPES
) != 0,
683 * g_spawn_command_line_sync:
684 * @command_line: a command line
685 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
686 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
687 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
688 * @error: return location for errors
690 * A simple version of g_spawn_sync() with little-used parameters
691 * removed, taking a command line instead of an argument vector. See
692 * g_spawn_sync() for full details. @command_line will be parsed by
693 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
694 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
695 * implications, so consider using g_spawn_sync() directly if
696 * appropriate. Possible errors are those from g_spawn_sync() and those
697 * from g_shell_parse_argv().
699 * If @exit_status is non-%NULL, the platform-specific exit status of
700 * the child is stored there; see the documentation of
701 * g_spawn_check_exit_status() for how to use and interpret this.
703 * On Windows, please note the implications of g_shell_parse_argv()
704 * parsing @command_line. Parsing is done according to Unix shell rules, not
705 * Windows command interpreter rules.
706 * Space is a separator, and backslashes are
707 * special. Thus you cannot simply pass a @command_line containing
708 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
709 * the backslashes will be eaten, and the space will act as a
710 * separator. You need to enclose such paths with single quotes, like
711 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
713 * Returns: %TRUE on success, %FALSE if an error was set
716 g_spawn_command_line_sync (const gchar
*command_line
,
717 gchar
**standard_output
,
718 gchar
**standard_error
,
725 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
727 if (!g_shell_parse_argv (command_line
,
732 retval
= g_spawn_sync (NULL
,
748 * g_spawn_command_line_async:
749 * @command_line: a command line
750 * @error: return location for errors
752 * A simple version of g_spawn_async() that parses a command line with
753 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
754 * command line in the background. Unlike g_spawn_async(), the
755 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
756 * that %G_SPAWN_SEARCH_PATH can have security implications, so
757 * consider using g_spawn_async() directly if appropriate. Possible
758 * errors are those from g_shell_parse_argv() and g_spawn_async().
760 * The same concerns on Windows apply as for g_spawn_command_line_sync().
762 * Returns: %TRUE on success, %FALSE if error is set
765 g_spawn_command_line_async (const gchar
*command_line
,
771 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
773 if (!g_shell_parse_argv (command_line
,
778 retval
= g_spawn_async (NULL
,
792 * g_spawn_check_exit_status:
793 * @exit_status: An exit code as returned from g_spawn_sync()
796 * Set @error if @exit_status indicates the child exited abnormally
797 * (e.g. with a nonzero exit code, or via a fatal signal).
799 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
800 * exit status for subprocesses encoded in a platform-specific way.
801 * On Unix, this is guaranteed to be in the same format waitpid() returns,
802 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
804 * Prior to the introduction of this function in GLib 2.34, interpreting
805 * @exit_status required use of platform-specific APIs, which is problematic
806 * for software using GLib as a cross-platform layer.
808 * Additionally, many programs simply want to determine whether or not
809 * the child exited successfully, and either propagate a #GError or
810 * print a message to standard error. In that common case, this function
811 * can be used. Note that the error message in @error will contain
812 * human-readable information about the exit status.
814 * The @domain and @code of @error have special semantics in the case
815 * where the process has an "exit code", as opposed to being killed by
816 * a signal. On Unix, this happens if WIFEXITED() would be true of
817 * @exit_status. On Windows, it is always the case.
819 * The special semantics are that the actual exit code will be the
820 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
821 * This allows you to differentiate between different exit codes.
823 * If the process was terminated by some means other than an exit
824 * status, the domain will be %G_SPAWN_ERROR, and the code will be
825 * %G_SPAWN_ERROR_FAILED.
827 * This function just offers convenience; you can of course also check
828 * the available platform via a macro such as %G_OS_UNIX, and use
829 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
830 * to scan or parse the error message string; it may be translated and/or
831 * change in future versions of GLib.
833 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
834 * @error will be set)
839 g_spawn_check_exit_status (gint exit_status
,
842 gboolean ret
= FALSE
;
844 if (WIFEXITED (exit_status
))
846 if (WEXITSTATUS (exit_status
) != 0)
848 g_set_error (error
, G_SPAWN_EXIT_ERROR
, WEXITSTATUS (exit_status
),
849 _("Child process exited with code %ld"),
850 (long) WEXITSTATUS (exit_status
));
854 else if (WIFSIGNALED (exit_status
))
856 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
857 _("Child process killed by signal %ld"),
858 (long) WTERMSIG (exit_status
));
861 else if (WIFSTOPPED (exit_status
))
863 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
864 _("Child process stopped by signal %ld"),
865 (long) WSTOPSIG (exit_status
));
870 g_set_error (error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
,
871 _("Child process exited abnormally"));
881 exec_err_to_g_error (gint en
)
887 return G_SPAWN_ERROR_ACCES
;
893 return G_SPAWN_ERROR_PERM
;
899 return G_SPAWN_ERROR_TOO_BIG
;
905 return G_SPAWN_ERROR_NOEXEC
;
911 return G_SPAWN_ERROR_NAMETOOLONG
;
917 return G_SPAWN_ERROR_NOENT
;
923 return G_SPAWN_ERROR_NOMEM
;
929 return G_SPAWN_ERROR_NOTDIR
;
935 return G_SPAWN_ERROR_LOOP
;
941 return G_SPAWN_ERROR_TXTBUSY
;
947 return G_SPAWN_ERROR_IO
;
953 return G_SPAWN_ERROR_NFILE
;
959 return G_SPAWN_ERROR_MFILE
;
965 return G_SPAWN_ERROR_INVAL
;
971 return G_SPAWN_ERROR_ISDIR
;
977 return G_SPAWN_ERROR_LIBBAD
;
982 return G_SPAWN_ERROR_FAILED
;
988 write_all (gint fd
, gconstpointer vbuf
, gsize to_write
)
990 gchar
*buf
= (gchar
*) vbuf
;
994 gssize count
= write (fd
, buf
, to_write
);
1012 write_err_and_exit (gint fd
, gint msg
)
1016 write_all (fd
, &msg
, sizeof(msg
));
1017 write_all (fd
, &en
, sizeof(en
));
1023 set_cloexec (void *data
, gint fd
)
1025 if (fd
>= GPOINTER_TO_INT (data
))
1026 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
1033 fdwalk (int (*cb
)(void *data
, int fd
), void *data
)
1039 #ifdef HAVE_SYS_RESOURCE_H
1046 if ((d
= opendir("/proc/self/fd"))) {
1049 while ((de
= readdir(d
))) {
1053 if (de
->d_name
[0] == '.')
1057 l
= strtol(de
->d_name
, &e
, 10);
1058 if (errno
!= 0 || !e
|| *e
)
1063 if ((glong
) fd
!= l
)
1069 if ((res
= cb (data
, fd
)) != 0)
1077 /* If /proc is not mounted or not accessible we fall back to the old
1082 #ifdef HAVE_SYS_RESOURCE_H
1084 if (getrlimit(RLIMIT_NOFILE
, &rl
) == 0 && rl
.rlim_max
!= RLIM_INFINITY
)
1085 open_max
= rl
.rlim_max
;
1088 open_max
= sysconf (_SC_OPEN_MAX
);
1090 for (fd
= 0; fd
< open_max
; fd
++)
1091 if ((res
= cb (data
, fd
)) != 0)
1099 sane_dup2 (gint fd1
, gint fd2
)
1104 ret
= dup2 (fd1
, fd2
);
1105 if (ret
< 0 && errno
== EINTR
)
1112 sane_open (const char *path
, gint mode
)
1117 ret
= open (path
, mode
);
1118 if (ret
< 0 && errno
== EINTR
)
1133 do_exec (gint child_err_report_fd
,
1137 const gchar
*working_directory
,
1140 gboolean close_descriptors
,
1141 gboolean search_path
,
1142 gboolean search_path_from_envp
,
1143 gboolean stdout_to_null
,
1144 gboolean stderr_to_null
,
1145 gboolean child_inherits_stdin
,
1146 gboolean file_and_argv_zero
,
1147 GSpawnChildSetupFunc child_setup
,
1150 if (working_directory
&& chdir (working_directory
) < 0)
1151 write_err_and_exit (child_err_report_fd
,
1152 CHILD_CHDIR_FAILED
);
1154 /* Close all file descriptors but stdin stdout and stderr as
1155 * soon as we exec. Note that this includes
1156 * child_err_report_fd, which keeps the parent from blocking
1157 * forever on the other end of that pipe.
1159 if (close_descriptors
)
1161 fdwalk (set_cloexec
, GINT_TO_POINTER(3));
1165 /* We need to do child_err_report_fd anyway */
1166 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd
);
1169 /* Redirect pipes as required */
1173 /* dup2 can't actually fail here I don't think */
1175 if (sane_dup2 (stdin_fd
, 0) < 0)
1176 write_err_and_exit (child_err_report_fd
,
1179 /* ignore this if it doesn't work */
1180 close_and_invalidate (&stdin_fd
);
1182 else if (!child_inherits_stdin
)
1184 /* Keep process from blocking on a read of stdin */
1185 gint read_null
= open ("/dev/null", O_RDONLY
);
1186 g_assert (read_null
!= -1);
1187 sane_dup2 (read_null
, 0);
1188 close_and_invalidate (&read_null
);
1193 /* dup2 can't actually fail here I don't think */
1195 if (sane_dup2 (stdout_fd
, 1) < 0)
1196 write_err_and_exit (child_err_report_fd
,
1199 /* ignore this if it doesn't work */
1200 close_and_invalidate (&stdout_fd
);
1202 else if (stdout_to_null
)
1204 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1205 g_assert (write_null
!= -1);
1206 sane_dup2 (write_null
, 1);
1207 close_and_invalidate (&write_null
);
1212 /* dup2 can't actually fail here I don't think */
1214 if (sane_dup2 (stderr_fd
, 2) < 0)
1215 write_err_and_exit (child_err_report_fd
,
1218 /* ignore this if it doesn't work */
1219 close_and_invalidate (&stderr_fd
);
1221 else if (stderr_to_null
)
1223 gint write_null
= sane_open ("/dev/null", O_WRONLY
);
1224 sane_dup2 (write_null
, 2);
1225 close_and_invalidate (&write_null
);
1228 /* Call user function just before we exec */
1231 (* child_setup
) (user_data
);
1235 file_and_argv_zero
? argv
+ 1 : argv
,
1236 envp
, search_path
, search_path_from_envp
);
1239 write_err_and_exit (child_err_report_fd
,
1256 if (bytes
>= sizeof(gint
)*2)
1257 break; /* give up, who knows what happened, should not be
1263 ((gchar
*)buf
) + bytes
,
1264 sizeof(gint
) * n_ints_in_buf
- bytes
);
1265 if (chunk
< 0 && errno
== EINTR
)
1272 /* Some weird shit happened, bail out */
1275 G_SPAWN_ERROR_FAILED
,
1276 _("Failed to read from child pipe (%s)"),
1277 g_strerror (errsv
));
1281 else if (chunk
== 0)
1283 else /* chunk > 0 */
1287 *n_ints_read
= (gint
)(bytes
/ sizeof(gint
));
1293 fork_exec_with_pipes (gboolean intermediate_child
,
1294 const gchar
*working_directory
,
1297 gboolean close_descriptors
,
1298 gboolean search_path
,
1299 gboolean search_path_from_envp
,
1300 gboolean stdout_to_null
,
1301 gboolean stderr_to_null
,
1302 gboolean child_inherits_stdin
,
1303 gboolean file_and_argv_zero
,
1304 gboolean cloexec_pipes
,
1305 GSpawnChildSetupFunc child_setup
,
1308 gint
*standard_input
,
1309 gint
*standard_output
,
1310 gint
*standard_error
,
1314 gint stdin_pipe
[2] = { -1, -1 };
1315 gint stdout_pipe
[2] = { -1, -1 };
1316 gint stderr_pipe
[2] = { -1, -1 };
1317 gint child_err_report_pipe
[2] = { -1, -1 };
1318 gint child_pid_report_pipe
[2] = { -1, -1 };
1319 guint pipe_flags
= cloexec_pipes
? FD_CLOEXEC
: 0;
1322 if (!g_unix_open_pipe (child_err_report_pipe
, pipe_flags
, error
))
1325 if (intermediate_child
&& !g_unix_open_pipe (child_pid_report_pipe
, pipe_flags
, error
))
1326 goto cleanup_and_fail
;
1328 if (standard_input
&& !g_unix_open_pipe (stdin_pipe
, pipe_flags
, error
))
1329 goto cleanup_and_fail
;
1331 if (standard_output
&& !g_unix_open_pipe (stdout_pipe
, pipe_flags
, error
))
1332 goto cleanup_and_fail
;
1334 if (standard_error
&& !g_unix_open_pipe (stderr_pipe
, FD_CLOEXEC
, error
))
1335 goto cleanup_and_fail
;
1346 _("Failed to fork (%s)"),
1347 g_strerror (errsv
));
1349 goto cleanup_and_fail
;
1353 /* Immediate child. This may or may not be the child that
1354 * actually execs the new process.
1357 /* Reset some signal handlers that we may use */
1358 signal (SIGCHLD
, SIG_DFL
);
1359 signal (SIGINT
, SIG_DFL
);
1360 signal (SIGTERM
, SIG_DFL
);
1361 signal (SIGHUP
, SIG_DFL
);
1363 /* Be sure we crash if the parent exits
1364 * and we write to the err_report_pipe
1366 signal (SIGPIPE
, SIG_DFL
);
1368 /* Close the parent's end of the pipes;
1369 * not needed in the close_descriptors case,
1372 close_and_invalidate (&child_err_report_pipe
[0]);
1373 close_and_invalidate (&child_pid_report_pipe
[0]);
1374 close_and_invalidate (&stdin_pipe
[1]);
1375 close_and_invalidate (&stdout_pipe
[0]);
1376 close_and_invalidate (&stderr_pipe
[0]);
1378 if (intermediate_child
)
1380 /* We need to fork an intermediate child that launches the
1381 * final child. The purpose of the intermediate child
1382 * is to exit, so we can waitpid() it immediately.
1383 * Then the grandchild will not become a zombie.
1385 GPid grandchild_pid
;
1387 grandchild_pid
= fork ();
1389 if (grandchild_pid
< 0)
1391 /* report -1 as child PID */
1392 write_all (child_pid_report_pipe
[1], &grandchild_pid
,
1393 sizeof(grandchild_pid
));
1395 write_err_and_exit (child_err_report_pipe
[1],
1398 else if (grandchild_pid
== 0)
1400 close_and_invalidate (&child_pid_report_pipe
[1]);
1401 do_exec (child_err_report_pipe
[1],
1410 search_path_from_envp
,
1413 child_inherits_stdin
,
1420 write_all (child_pid_report_pipe
[1], &grandchild_pid
, sizeof(grandchild_pid
));
1421 close_and_invalidate (&child_pid_report_pipe
[1]);
1428 /* Just run the child.
1431 do_exec (child_err_report_pipe
[1],
1440 search_path_from_envp
,
1443 child_inherits_stdin
,
1456 /* Close the uncared-about ends of the pipes */
1457 close_and_invalidate (&child_err_report_pipe
[1]);
1458 close_and_invalidate (&child_pid_report_pipe
[1]);
1459 close_and_invalidate (&stdin_pipe
[0]);
1460 close_and_invalidate (&stdout_pipe
[1]);
1461 close_and_invalidate (&stderr_pipe
[1]);
1463 /* If we had an intermediate child, reap it */
1464 if (intermediate_child
)
1467 if (waitpid (pid
, &status
, 0) < 0)
1471 else if (errno
== ECHILD
)
1472 ; /* do nothing, child already reaped */
1474 g_warning ("waitpid() should not fail in "
1475 "'fork_exec_with_pipes'");
1480 if (!read_ints (child_err_report_pipe
[0],
1483 goto cleanup_and_fail
;
1487 /* Error from the child. */
1491 case CHILD_CHDIR_FAILED
:
1494 G_SPAWN_ERROR_CHDIR
,
1495 _("Failed to change to directory '%s' (%s)"),
1497 g_strerror (buf
[1]));
1501 case CHILD_EXEC_FAILED
:
1504 exec_err_to_g_error (buf
[1]),
1505 _("Failed to execute child process \"%s\" (%s)"),
1507 g_strerror (buf
[1]));
1511 case CHILD_DUP2_FAILED
:
1514 G_SPAWN_ERROR_FAILED
,
1515 _("Failed to redirect output or input of child process (%s)"),
1516 g_strerror (buf
[1]));
1520 case CHILD_FORK_FAILED
:
1524 _("Failed to fork child process (%s)"),
1525 g_strerror (buf
[1]));
1531 G_SPAWN_ERROR_FAILED
,
1532 _("Unknown error executing child process \"%s\""),
1537 goto cleanup_and_fail
;
1540 /* Get child pid from intermediate child pipe. */
1541 if (intermediate_child
)
1545 if (!read_ints (child_pid_report_pipe
[0],
1546 buf
, 1, &n_ints
, error
))
1547 goto cleanup_and_fail
;
1555 G_SPAWN_ERROR_FAILED
,
1556 _("Failed to read enough data from child pid pipe (%s)"),
1557 g_strerror (errsv
));
1558 goto cleanup_and_fail
;
1562 /* we have the child pid */
1567 /* Success against all odds! return the information */
1568 close_and_invalidate (&child_err_report_pipe
[0]);
1569 close_and_invalidate (&child_pid_report_pipe
[0]);
1575 *standard_input
= stdin_pipe
[1];
1576 if (standard_output
)
1577 *standard_output
= stdout_pipe
[0];
1579 *standard_error
= stderr_pipe
[0];
1586 /* There was an error from the Child, reap the child to avoid it being
1593 if (waitpid (pid
, NULL
, 0) < 0)
1597 else if (errno
== ECHILD
)
1598 ; /* do nothing, child already reaped */
1600 g_warning ("waitpid() should not fail in "
1601 "'fork_exec_with_pipes'");
1605 close_and_invalidate (&child_err_report_pipe
[0]);
1606 close_and_invalidate (&child_err_report_pipe
[1]);
1607 close_and_invalidate (&child_pid_report_pipe
[0]);
1608 close_and_invalidate (&child_pid_report_pipe
[1]);
1609 close_and_invalidate (&stdin_pipe
[0]);
1610 close_and_invalidate (&stdin_pipe
[1]);
1611 close_and_invalidate (&stdout_pipe
[0]);
1612 close_and_invalidate (&stdout_pipe
[1]);
1613 close_and_invalidate (&stderr_pipe
[0]);
1614 close_and_invalidate (&stderr_pipe
[1]);
1619 /* Based on execvp from GNU C Library */
1622 script_execute (const gchar
*file
,
1626 /* Count the arguments. */
1631 /* Construct an argument list for the shell. */
1635 new_argv
= g_new0 (gchar
*, argc
+ 2); /* /bin/sh and NULL */
1637 new_argv
[0] = (char *) "/bin/sh";
1638 new_argv
[1] = (char *) file
;
1641 new_argv
[argc
+ 1] = argv
[argc
];
1645 /* Execute the shell. */
1647 execve (new_argv
[0], new_argv
, envp
);
1649 execv (new_argv
[0], new_argv
);
1656 my_strchrnul (const gchar
*str
, gchar c
)
1658 gchar
*p
= (gchar
*) str
;
1659 while (*p
&& (*p
!= c
))
1666 g_execute (const gchar
*file
,
1669 gboolean search_path
,
1670 gboolean search_path_from_envp
)
1674 /* We check the simple case first. */
1679 if (!(search_path
|| search_path_from_envp
) || strchr (file
, '/') != NULL
)
1681 /* Don't search when it contains a slash. */
1683 execve (file
, argv
, envp
);
1687 if (errno
== ENOEXEC
)
1688 script_execute (file
, argv
, envp
);
1692 gboolean got_eacces
= 0;
1693 const gchar
*path
, *p
;
1694 gchar
*name
, *freeme
;
1699 if (search_path_from_envp
)
1700 path
= g_environ_getenv (envp
, "PATH");
1701 if (search_path
&& path
== NULL
)
1702 path
= g_getenv ("PATH");
1706 /* There is no 'PATH' in the environment. The default
1707 * search path in libc is the current directory followed by
1708 * the path 'confstr' returns for '_CS_PATH'.
1711 /* In GLib we put . last, for security, and don't use the
1712 * unportable confstr(); UNIX98 does not actually specify
1713 * what to search if PATH is unset. POSIX may, dunno.
1716 path
= "/bin:/usr/bin:.";
1719 len
= strlen (file
) + 1;
1720 pathlen
= strlen (path
);
1721 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
1723 /* Copy the file name at the top, including '\0' */
1724 memcpy (name
+ pathlen
+ 1, file
, len
);
1725 name
= name
+ pathlen
;
1726 /* And add the slash before the filename */
1735 p
= my_strchrnul (path
, ':');
1738 /* Two adjacent colons, or a colon at the beginning or the end
1739 * of 'PATH' means to search the current directory.
1743 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
1745 /* Try to execute this name. If it works, execv will not return. */
1747 execve (startp
, argv
, envp
);
1749 execv (startp
, argv
);
1751 if (errno
== ENOEXEC
)
1752 script_execute (startp
, argv
, envp
);
1757 /* Record the we got a 'Permission denied' error. If we end
1758 * up finding no executable we can use, we want to diagnose
1759 * that we did find one but were denied access.
1772 /* Those errors indicate the file is missing or not executable
1773 * by us, in which case we want to just try the next path
1780 /* Some strange filesystems like AFS return even
1781 * stranger error numbers. They cannot reasonably mean anything
1782 * else so ignore those, too.
1787 /* Some other error means we found an executable file, but
1788 * something went wrong executing it; return the error to our
1795 while (*p
++ != '\0');
1797 /* We tried every element and none of them worked. */
1799 /* At least one failure was due to permissions, so report that
1807 /* Return the error from the last attempt (probably ENOENT). */
1812 * g_spawn_close_pid:
1813 * @pid: The process reference to close
1815 * On some platforms, notably Windows, the #GPid type represents a resource
1816 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1817 * is provided for this purpose. It should be used on all platforms, even
1818 * though it doesn't do anything under UNIX.
1821 g_spawn_close_pid (GPid pid
)