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 */
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
60 * @Short_description: process launching
61 * @Title: Spawning Processes
66 static gint g_execute (const gchar *file,
70 gboolean search_path_from_envp);
72 static gboolean make_pipe (gint p[2],
74 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
75 const gchar *working_directory,
78 gboolean close_descriptors,
80 gboolean search_path_from_envp,
81 gboolean stdout_to_null,
82 gboolean stderr_to_null,
83 gboolean child_inherits_stdin,
84 gboolean file_and_argv_zero,
85 GSpawnChildSetupFunc child_setup,
89 gint *standard_output,
93 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
94 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
98 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
99 * @argv: (array zero-terminated=1): child's argument vector
100 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
101 * @flags: flags from #GSpawnFlags
102 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
103 * @user_data: (closure): user data for @child_setup
104 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
105 * @error: return location for error
107 * See g_spawn_async_with_pipes() for a full description; this function
108 * simply calls the g_spawn_async_with_pipes() without any pipes.
110 * You should call g_spawn_close_pid() on the returned child process
111 * reference when you don't need it any more.
114 * If you are writing a GTK+ application, and the program you
115 * are spawning is a graphical application, too, then you may
116 * want to use gdk_spawn_on_screen() instead to ensure that
117 * the spawned program opens its windows on the right screen.
120 * <note><para> Note that the returned @child_pid on Windows is a
121 * handle to the child process and not its identifier. Process handles
122 * and process identifiers are different concepts on Windows.
125 * Return value: %TRUE on success, %FALSE if error is set
128 g_spawn_async (const gchar *working_directory,
132 GSpawnChildSetupFunc child_setup,
137 g_return_val_if_fail (argv != NULL, FALSE);
139 return g_spawn_async_with_pipes (working_directory,
149 /* Avoids a danger in threaded situations (calling close()
150 * on a file descriptor twice, and another thread has
151 * re-opened it since the first close)
154 close_and_invalidate (gint *fd)
164 if (ret == -1 && errno == EINTR)
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)"),
222 on_sync_waitpid (GPid pid,
226 SyncWaitpidData *data = user_data;
227 *(data->status_p) = status;
228 g_main_loop_quit (data->loop);
233 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
234 * @argv: (array zero-terminated=1): child's argument vector
235 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
236 * @flags: flags from #GSpawnFlags
237 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
238 * @user_data: (closure): user data for @child_setup
239 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
240 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
241 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
242 * @error: return location for error, or %NULL
244 * Executes a child synchronously (waits for the child to exit before returning).
245 * All output from the child is stored in @standard_output and @standard_error,
246 * if those parameters are non-%NULL. Note that you must set the
247 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
248 * passing %NULL for @standard_output and @standard_error.
250 * If @exit_status is non-%NULL, the platform-specific exit status of
251 * the child is stored there; see the doucumentation of
252 * g_spawn_check_exit_status() for how to use and interpret this.
253 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
256 * If an error occurs, no data is returned in @standard_output,
257 * @standard_error, or @exit_status.
259 * This function calls g_spawn_async_with_pipes() internally; see that
260 * function for full details on the other parameters and details on
261 * how these functions work on Windows.
263 * Return value: %TRUE on success, %FALSE if an error was set.
266 g_spawn_sync (const gchar *working_directory,
270 GSpawnChildSetupFunc child_setup,
272 gchar **standard_output,
273 gchar **standard_error,
282 GString *outstr = NULL;
283 GString *errstr = NULL;
286 SyncWaitpidData waitpid_data;
288 g_return_val_if_fail (argv != NULL, FALSE);
289 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
290 g_return_val_if_fail (standard_output == NULL ||
291 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
292 g_return_val_if_fail (standard_error == NULL ||
293 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
295 /* Just to ensure segfaults if callers try to use
296 * these when an error is reported.
299 *standard_output = NULL;
302 *standard_error = NULL;
304 if (!fork_exec_with_pipes (FALSE,
308 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
309 (flags & G_SPAWN_SEARCH_PATH) != 0,
310 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
311 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
312 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
313 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
314 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
319 standard_output ? &outpipe : NULL,
320 standard_error ? &errpipe : NULL,
324 /* Read data from child. */
330 outstr = g_string_new (NULL);
335 errstr = g_string_new (NULL);
338 /* Read data until we get EOF on both pipes. */
347 FD_SET (outpipe, &fds);
349 FD_SET (errpipe, &fds);
351 ret = select (MAX (outpipe, errpipe) + 1,
354 NULL /* no timeout */);
368 _("Unexpected error in select() reading data from a child process (%s)"),
374 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
376 switch (read_data (outstr, outpipe, error))
382 close_and_invalidate (&outpipe);
393 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
395 switch (read_data (errstr, errpipe, error))
401 close_and_invalidate (&errpipe);
413 /* These should only be open still if we had an error. */
416 close_and_invalidate (&outpipe);
418 close_and_invalidate (&errpipe);
420 /* Now create a temporary main context and loop, with just one
421 * waitpid source. We used to invoke waitpid() directly here, but
422 * this way we unify with the worker thread in gmain.c.
425 GMainContext *context;
429 context = g_main_context_new ();
430 loop = g_main_loop_new (context, TRUE);
432 waitpid_data.loop = loop;
433 waitpid_data.status_p = &status;
435 source = g_child_watch_source_new (pid);
436 g_source_set_callback (source, (GSourceFunc)on_sync_waitpid, &waitpid_data, NULL);
437 g_source_attach (source, context);
438 g_source_unref (source);
440 g_main_loop_run (loop);
442 g_main_context_unref (context);
443 g_main_loop_unref (loop);
449 g_string_free (outstr, TRUE);
451 g_string_free (errstr, TRUE);
458 *exit_status = status;
461 *standard_output = g_string_free (outstr, FALSE);
464 *standard_error = g_string_free (errstr, FALSE);
471 * g_spawn_async_with_pipes:
472 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
473 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
474 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
475 * @flags: flags from #GSpawnFlags
476 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
477 * @user_data: (closure): user data for @child_setup
478 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
479 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
480 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
481 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
482 * @error: return location for error
484 * Executes a child program asynchronously (your program will not
485 * block waiting for the child to exit). The child program is
486 * specified by the only argument that must be provided, @argv. @argv
487 * should be a %NULL-terminated array of strings, to be passed as the
488 * argument vector for the child. The first string in @argv is of
489 * course the name of the program to execute. By default, the name of
490 * the program must be a full path. If @flags contains the
491 * %G_SPAWN_SEARCH_PATH flag, the <envar>PATH</envar> environment variable
492 * is used to search for the executable. If @flags contains the
493 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the <envar>PATH</envar> variable from
494 * @envp is used to search for the executable.
495 * If both the %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
496 * flags are set, the <envar>PATH</envar> variable from @envp takes precedence
497 * over the environment variable.
499 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
500 * used, then the program will be run from the current directory (or
501 * @working_directory, if specified); this might be unexpected or even
502 * dangerous in some cases when the current directory is world-writable.
504 * On Windows, note that all the string or string vector arguments to
505 * this function and the other g_spawn*() functions are in UTF-8, the
506 * GLib file name encoding. Unicode characters that are not part of
507 * the system codepage passed in these arguments will be correctly
508 * available in the spawned program only if it uses wide character API
509 * to retrieve its command line. For C programs built with Microsoft's
510 * tools it is enough to make the program have a wmain() instead of
511 * main(). wmain() has a wide character argument vector as parameter.
513 * At least currently, mingw doesn't support wmain(), so if you use
514 * mingw to develop the spawned program, it will have to call the
515 * undocumented function __wgetmainargs() to get the wide character
516 * argument vector and environment. See gspawn-win32-helper.c in the
517 * GLib sources or init.c in the mingw runtime sources for a prototype
518 * for that function. Alternatively, you can retrieve the Win32 system
519 * level wide character command line passed to the spawned program
520 * using the GetCommandLineW() function.
522 * On Windows the low-level child process creation API
523 * <function>CreateProcess()</function> doesn't use argument vectors,
524 * but a command line. The C runtime library's
525 * <function>spawn*()</function> family of functions (which
526 * g_spawn_async_with_pipes() eventually calls) paste the argument
527 * vector elements together into a command line, and the C runtime startup code
528 * does a corresponding reconstruction of an argument vector from the
529 * command line, to be passed to main(). Complications arise when you have
530 * argument vector elements that contain spaces of double quotes. The
531 * <function>spawn*()</function> functions don't do any quoting or
532 * escaping, but on the other hand the startup code does do unquoting
533 * and unescaping in order to enable receiving arguments with embedded
534 * spaces or double quotes. To work around this asymmetry,
535 * g_spawn_async_with_pipes() will do quoting and escaping on argument
536 * vector elements that need it before calling the C runtime
539 * The returned @child_pid on Windows is a handle to the child
540 * process, not its identifier. Process handles and process
541 * identifiers are different concepts on Windows.
543 * @envp is a %NULL-terminated array of strings, where each string
544 * has the form <literal>KEY=VALUE</literal>. This will become
545 * the child's environment. If @envp is %NULL, the child inherits its
546 * parent's environment.
548 * @flags should be the bitwise OR of any flags you want to affect the
549 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
550 * child will not automatically be reaped; you must use a child watch to
551 * be notified about the death of the child process. Eventually you must
552 * call g_spawn_close_pid() on the @child_pid, in order to free
553 * resources which may be associated with the child process. (On Unix,
554 * using a child watch is equivalent to calling waitpid() or handling
555 * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
556 * is equivalent to calling CloseHandle() on the process handle returned
557 * in @child_pid). See g_child_watch_add().
559 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
560 * descriptors will be inherited by the child; otherwise all
561 * descriptors except stdin/stdout/stderr will be closed before
562 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
563 * means that <literal>argv[0]</literal> need not be an absolute path, it
564 * will be looked for in the <envar>PATH</envar> environment variable.
565 * %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an absolute path, it
566 * will be looked for in the <envar>PATH</envar> variable from @envp. If
567 * both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP are used,
568 * the value from @envp takes precedence over the environment.
569 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
570 * be discarded, instead of going to the same location as the parent's
571 * standard output. If you use this flag, @standard_output must be %NULL.
572 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
573 * will be discarded, instead of going to the same location as the parent's
574 * standard error. If you use this flag, @standard_error must be %NULL.
575 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
576 * standard input (by default, the child's standard input is attached to
577 * /dev/null). If you use this flag, @standard_input must be %NULL.
578 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
579 * the file to execute, while the remaining elements are the
580 * actual argument vector to pass to the file. Normally
581 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
582 * passes all of @argv to the child.
584 * @child_setup and @user_data are a function and user data. On POSIX
585 * platforms, the function is called in the child after GLib has
586 * performed all the setup it plans to perform (including creating
587 * pipes, closing file descriptors, etc.) but before calling
588 * exec(). That is, @child_setup is called just
589 * before calling exec() in the child. Obviously
590 * actions taken in this function will only affect the child, not the
593 * On Windows, there is no separate fork() and exec()
594 * functionality. Child processes are created and run with a single
595 * API call, CreateProcess(). There is no sensible thing @child_setup
596 * could be used for on Windows so it is ignored and not called.
598 * If non-%NULL, @child_pid will on Unix be filled with the child's
599 * process ID. You can use the process ID to send signals to the
600 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
601 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
602 * filled with a handle to the child process only if you specified the
603 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
604 * process using the Win32 API, for example wait for its termination
605 * with the <function>WaitFor*()</function> functions, or examine its
606 * exit code with GetExitCodeProcess(). You should close the handle
607 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
609 * If non-%NULL, the @standard_input, @standard_output, @standard_error
610 * locations will be filled with file descriptors for writing to the child's
611 * standard input or reading from its standard output or standard error.
612 * The caller of g_spawn_async_with_pipes() must close these file descriptors
613 * when they are no longer in use. If these parameters are %NULL, the corresponding
614 * pipe won't be created.
616 * If @standard_input is NULL, the child's standard input is attached to
617 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
619 * If @standard_error is NULL, the child's standard error goes to the same
620 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
623 * If @standard_output is NULL, the child's standard output goes to the same
624 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
627 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
628 * If an error is set, the function returns %FALSE. Errors
629 * are reported even if they occur in the child (for example if the
630 * executable in <literal>argv[0]</literal> is not found). Typically
631 * the <literal>message</literal> field of returned errors should be displayed
632 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
634 * If an error occurs, @child_pid, @standard_input, @standard_output,
635 * and @standard_error will not be filled with valid values.
637 * If @child_pid is not %NULL and an error does not occur then the returned
638 * process reference must be closed using g_spawn_close_pid().
641 * If you are writing a GTK+ application, and the program you
642 * are spawning is a graphical application, too, then you may
643 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
644 * the spawned program opens its windows on the right screen.
647 * Return value: %TRUE on success, %FALSE if an error was set
650 g_spawn_async_with_pipes (const gchar *working_directory,
654 GSpawnChildSetupFunc child_setup,
657 gint *standard_input,
658 gint *standard_output,
659 gint *standard_error,
662 g_return_val_if_fail (argv != NULL, FALSE);
663 g_return_val_if_fail (standard_output == NULL ||
664 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
665 g_return_val_if_fail (standard_error == NULL ||
666 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
667 /* can't inherit stdin if we have an input pipe. */
668 g_return_val_if_fail (standard_input == NULL ||
669 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
671 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
675 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
676 (flags & G_SPAWN_SEARCH_PATH) != 0,
677 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
678 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
679 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
680 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
681 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
692 * g_spawn_command_line_sync:
693 * @command_line: a command line
694 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
695 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
696 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
697 * @error: return location for errors
699 * A simple version of g_spawn_sync() with little-used parameters
700 * removed, taking a command line instead of an argument vector. See
701 * g_spawn_sync() for full details. @command_line will be parsed by
702 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
703 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
704 * implications, so consider using g_spawn_sync() directly if
705 * appropriate. Possible errors are those from g_spawn_sync() and those
706 * from g_shell_parse_argv().
708 * If @exit_status is non-%NULL, the platform-specific exit status of
709 * the child is stored there; see the documentation of
710 * g_spawn_check_exit_status() for how to use and interpret this.
712 * On Windows, please note the implications of g_shell_parse_argv()
713 * parsing @command_line. Parsing is done according to Unix shell rules, not
714 * Windows command interpreter rules.
715 * Space is a separator, and backslashes are
716 * special. Thus you cannot simply pass a @command_line containing
717 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
718 * the backslashes will be eaten, and the space will act as a
719 * separator. You need to enclose such paths with single quotes, like
720 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
722 * Return value: %TRUE on success, %FALSE if an error was set
725 g_spawn_command_line_sync (const gchar *command_line,
726 gchar **standard_output,
727 gchar **standard_error,
734 g_return_val_if_fail (command_line != NULL, FALSE);
736 if (!g_shell_parse_argv (command_line,
741 retval = g_spawn_sync (NULL,
757 * g_spawn_command_line_async:
758 * @command_line: a command line
759 * @error: return location for errors
761 * A simple version of g_spawn_async() that parses a command line with
762 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
763 * command line in the background. Unlike g_spawn_async(), the
764 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
765 * that %G_SPAWN_SEARCH_PATH can have security implications, so
766 * consider using g_spawn_async() directly if appropriate. Possible
767 * errors are those from g_shell_parse_argv() and g_spawn_async().
769 * The same concerns on Windows apply as for g_spawn_command_line_sync().
771 * Return value: %TRUE on success, %FALSE if error is set.
774 g_spawn_command_line_async (const gchar *command_line,
780 g_return_val_if_fail (command_line != NULL, FALSE);
782 if (!g_shell_parse_argv (command_line,
787 retval = g_spawn_async (NULL,
801 * g_spawn_check_exit_status:
802 * @exit_status: An exit code as returned from g_spawn_sync()
805 * Set @error if @exit_status indicates the child exited abnormally
806 * (e.g. with a nonzero exit code, or via a fatal signal).
808 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
809 * exit status for subprocesses encoded in a platform-specific way.
810 * On Unix, this is guaranteed to be in the same format
811 * <literal>waitpid(2)</literal> returns, and on Windows it is
812 * guaranteed to be the result of
813 * <literal>GetExitCodeProcess()</literal>. Prior to the introduction
814 * of this function in GLib 2.34, interpreting @exit_status required
815 * use of platform-specific APIs, which is problematic for software
816 * using GLib as a cross-platform layer.
818 * Additionally, many programs simply want to determine whether or not
819 * the child exited successfully, and either propagate a #GError or
820 * print a message to standard error. In that common case, this
821 * function can be used. Note that the error message in @error will
822 * contain human-readable information about the exit status.
824 * The <literal>domain</literal> and <literal>code</literal> of @error
825 * have special semantics in the case where the process has an "exit
826 * code", as opposed to being killed by a signal. On Unix, this
827 * happens if <literal>WIFEXITED</literal> would be true of
828 * @exit_status. On Windows, it is always the case.
830 * The special semantics are that the actual exit code will be the
831 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
832 * This allows you to differentiate between different exit codes.
834 * If the process was terminated by some means other than an exit
835 * status, the domain will be %G_SPAWN_ERROR, and the code will be
836 * %G_SPAWN_ERROR_FAILED.
838 * This function just offers convenience; you can of course also check
839 * the available platform via a macro such as %G_OS_UNIX, and use
840 * <literal>WIFEXITED()</literal> and <literal>WEXITSTATUS()</literal>
841 * on @exit_status directly. Do not attempt to scan or parse the
842 * error message string; it may be translated and/or change in future
845 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and @error will be set)
849 g_spawn_check_exit_status (gint exit_status,
852 gboolean ret = FALSE;
854 if (WIFEXITED (exit_status))
856 if (WEXITSTATUS (exit_status) != 0)
858 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
859 _("Child process exited with code %ld"),
860 (long) WEXITSTATUS (exit_status));
864 else if (WIFSIGNALED (exit_status))
866 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
867 _("Child process killed by signal %ld"),
868 (long) WTERMSIG (exit_status));
871 else if (WIFSTOPPED (exit_status))
873 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
874 _("Child process stopped by signal %ld"),
875 (long) WSTOPSIG (exit_status));
880 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
881 _("Child process exited abnormally"));
891 exec_err_to_g_error (gint en)
897 return G_SPAWN_ERROR_ACCES;
903 return G_SPAWN_ERROR_PERM;
909 return G_SPAWN_ERROR_TOO_BIG;
915 return G_SPAWN_ERROR_NOEXEC;
921 return G_SPAWN_ERROR_NAMETOOLONG;
927 return G_SPAWN_ERROR_NOENT;
933 return G_SPAWN_ERROR_NOMEM;
939 return G_SPAWN_ERROR_NOTDIR;
945 return G_SPAWN_ERROR_LOOP;
951 return G_SPAWN_ERROR_TXTBUSY;
957 return G_SPAWN_ERROR_IO;
963 return G_SPAWN_ERROR_NFILE;
969 return G_SPAWN_ERROR_MFILE;
975 return G_SPAWN_ERROR_INVAL;
981 return G_SPAWN_ERROR_ISDIR;
987 return G_SPAWN_ERROR_LIBBAD;
992 return G_SPAWN_ERROR_FAILED;
998 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1000 gchar *buf = (gchar *) vbuf;
1002 while (to_write > 0)
1004 gssize count = write (fd, buf, to_write);
1022 write_err_and_exit (gint fd, gint msg)
1026 write_all (fd, &msg, sizeof(msg));
1027 write_all (fd, &en, sizeof(en));
1033 set_cloexec (void *data, gint fd)
1035 if (fd >= GPOINTER_TO_INT (data))
1036 fcntl (fd, F_SETFD, FD_CLOEXEC);
1043 fdwalk (int (*cb)(void *data, int fd), void *data)
1049 #ifdef HAVE_SYS_RESOURCE_H
1056 if ((d = opendir("/proc/self/fd"))) {
1059 while ((de = readdir(d))) {
1063 if (de->d_name[0] == '.')
1067 l = strtol(de->d_name, &e, 10);
1068 if (errno != 0 || !e || *e)
1073 if ((glong) fd != l)
1079 if ((res = cb (data, fd)) != 0)
1087 /* If /proc is not mounted or not accessible we fall back to the old
1092 #ifdef HAVE_SYS_RESOURCE_H
1094 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1095 open_max = rl.rlim_max;
1098 open_max = sysconf (_SC_OPEN_MAX);
1100 for (fd = 0; fd < open_max; fd++)
1101 if ((res = cb (data, fd)) != 0)
1109 sane_dup2 (gint fd1, gint fd2)
1114 ret = dup2 (fd1, fd2);
1115 if (ret < 0 && errno == EINTR)
1122 sane_open (const char *path, gint mode)
1127 ret = open (path, mode);
1128 if (ret < 0 && errno == EINTR)
1143 do_exec (gint child_err_report_fd,
1147 const gchar *working_directory,
1150 gboolean close_descriptors,
1151 gboolean search_path,
1152 gboolean search_path_from_envp,
1153 gboolean stdout_to_null,
1154 gboolean stderr_to_null,
1155 gboolean child_inherits_stdin,
1156 gboolean file_and_argv_zero,
1157 GSpawnChildSetupFunc child_setup,
1160 if (working_directory && chdir (working_directory) < 0)
1161 write_err_and_exit (child_err_report_fd,
1162 CHILD_CHDIR_FAILED);
1164 /* Close all file descriptors but stdin stdout and stderr as
1165 * soon as we exec. Note that this includes
1166 * child_err_report_fd, which keeps the parent from blocking
1167 * forever on the other end of that pipe.
1169 if (close_descriptors)
1171 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1175 /* We need to do child_err_report_fd anyway */
1176 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1179 /* Redirect pipes as required */
1183 /* dup2 can't actually fail here I don't think */
1185 if (sane_dup2 (stdin_fd, 0) < 0)
1186 write_err_and_exit (child_err_report_fd,
1189 /* ignore this if it doesn't work */
1190 close_and_invalidate (&stdin_fd);
1192 else if (!child_inherits_stdin)
1194 /* Keep process from blocking on a read of stdin */
1195 gint read_null = open ("/dev/null", O_RDONLY);
1196 g_assert (read_null != -1);
1197 sane_dup2 (read_null, 0);
1198 close_and_invalidate (&read_null);
1203 /* dup2 can't actually fail here I don't think */
1205 if (sane_dup2 (stdout_fd, 1) < 0)
1206 write_err_and_exit (child_err_report_fd,
1209 /* ignore this if it doesn't work */
1210 close_and_invalidate (&stdout_fd);
1212 else if (stdout_to_null)
1214 gint write_null = sane_open ("/dev/null", O_WRONLY);
1215 g_assert (write_null != -1);
1216 sane_dup2 (write_null, 1);
1217 close_and_invalidate (&write_null);
1222 /* dup2 can't actually fail here I don't think */
1224 if (sane_dup2 (stderr_fd, 2) < 0)
1225 write_err_and_exit (child_err_report_fd,
1228 /* ignore this if it doesn't work */
1229 close_and_invalidate (&stderr_fd);
1231 else if (stderr_to_null)
1233 gint write_null = sane_open ("/dev/null", O_WRONLY);
1234 sane_dup2 (write_null, 2);
1235 close_and_invalidate (&write_null);
1238 /* Call user function just before we exec */
1241 (* child_setup) (user_data);
1245 file_and_argv_zero ? argv + 1 : argv,
1246 envp, search_path, search_path_from_envp);
1249 write_err_and_exit (child_err_report_fd,
1266 if (bytes >= sizeof(gint)*2)
1267 break; /* give up, who knows what happened, should not be
1273 ((gchar*)buf) + bytes,
1274 sizeof(gint) * n_ints_in_buf - bytes);
1275 if (chunk < 0 && errno == EINTR)
1282 /* Some weird shit happened, bail out */
1285 G_SPAWN_ERROR_FAILED,
1286 _("Failed to read from child pipe (%s)"),
1287 g_strerror (errsv));
1291 else if (chunk == 0)
1293 else /* chunk > 0 */
1297 *n_ints_read = (gint)(bytes / sizeof(gint));
1303 fork_exec_with_pipes (gboolean intermediate_child,
1304 const gchar *working_directory,
1307 gboolean close_descriptors,
1308 gboolean search_path,
1309 gboolean search_path_from_envp,
1310 gboolean stdout_to_null,
1311 gboolean stderr_to_null,
1312 gboolean child_inherits_stdin,
1313 gboolean file_and_argv_zero,
1314 GSpawnChildSetupFunc child_setup,
1317 gint *standard_input,
1318 gint *standard_output,
1319 gint *standard_error,
1323 gint stdin_pipe[2] = { -1, -1 };
1324 gint stdout_pipe[2] = { -1, -1 };
1325 gint stderr_pipe[2] = { -1, -1 };
1326 gint child_err_report_pipe[2] = { -1, -1 };
1327 gint child_pid_report_pipe[2] = { -1, -1 };
1330 if (!make_pipe (child_err_report_pipe, error))
1333 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1334 goto cleanup_and_fail;
1336 if (standard_input && !make_pipe (stdin_pipe, error))
1337 goto cleanup_and_fail;
1339 if (standard_output && !make_pipe (stdout_pipe, error))
1340 goto cleanup_and_fail;
1342 if (standard_error && !make_pipe (stderr_pipe, error))
1343 goto cleanup_and_fail;
1354 _("Failed to fork (%s)"),
1355 g_strerror (errsv));
1357 goto cleanup_and_fail;
1361 /* Immediate child. This may or may not be the child that
1362 * actually execs the new process.
1365 /* Reset some signal handlers that we may use */
1366 signal (SIGCHLD, SIG_DFL);
1367 signal (SIGINT, SIG_DFL);
1368 signal (SIGTERM, SIG_DFL);
1369 signal (SIGHUP, SIG_DFL);
1371 /* Be sure we crash if the parent exits
1372 * and we write to the err_report_pipe
1374 signal (SIGPIPE, SIG_DFL);
1376 /* Close the parent's end of the pipes;
1377 * not needed in the close_descriptors case,
1380 close_and_invalidate (&child_err_report_pipe[0]);
1381 close_and_invalidate (&child_pid_report_pipe[0]);
1382 close_and_invalidate (&stdin_pipe[1]);
1383 close_and_invalidate (&stdout_pipe[0]);
1384 close_and_invalidate (&stderr_pipe[0]);
1386 if (intermediate_child)
1388 /* We need to fork an intermediate child that launches the
1389 * final child. The purpose of the intermediate child
1390 * is to exit, so we can waitpid() it immediately.
1391 * Then the grandchild will not become a zombie.
1393 GPid grandchild_pid;
1395 grandchild_pid = fork ();
1397 if (grandchild_pid < 0)
1399 /* report -1 as child PID */
1400 write_all (child_pid_report_pipe[1], &grandchild_pid,
1401 sizeof(grandchild_pid));
1403 write_err_and_exit (child_err_report_pipe[1],
1406 else if (grandchild_pid == 0)
1408 do_exec (child_err_report_pipe[1],
1417 search_path_from_envp,
1420 child_inherits_stdin,
1427 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1428 close_and_invalidate (&child_pid_report_pipe[1]);
1435 /* Just run the child.
1438 do_exec (child_err_report_pipe[1],
1447 search_path_from_envp,
1450 child_inherits_stdin,
1463 /* Close the uncared-about ends of the pipes */
1464 close_and_invalidate (&child_err_report_pipe[1]);
1465 close_and_invalidate (&child_pid_report_pipe[1]);
1466 close_and_invalidate (&stdin_pipe[0]);
1467 close_and_invalidate (&stdout_pipe[1]);
1468 close_and_invalidate (&stderr_pipe[1]);
1470 /* If we had an intermediate child, reap it */
1471 if (intermediate_child)
1474 if (waitpid (pid, &status, 0) < 0)
1478 else if (errno == ECHILD)
1479 ; /* do nothing, child already reaped */
1481 g_warning ("waitpid() should not fail in "
1482 "'fork_exec_with_pipes'");
1487 if (!read_ints (child_err_report_pipe[0],
1490 goto cleanup_and_fail;
1494 /* Error from the child. */
1498 case CHILD_CHDIR_FAILED:
1501 G_SPAWN_ERROR_CHDIR,
1502 _("Failed to change to directory '%s' (%s)"),
1504 g_strerror (buf[1]));
1508 case CHILD_EXEC_FAILED:
1511 exec_err_to_g_error (buf[1]),
1512 _("Failed to execute child process \"%s\" (%s)"),
1514 g_strerror (buf[1]));
1518 case CHILD_DUP2_FAILED:
1521 G_SPAWN_ERROR_FAILED,
1522 _("Failed to redirect output or input of child process (%s)"),
1523 g_strerror (buf[1]));
1527 case CHILD_FORK_FAILED:
1531 _("Failed to fork child process (%s)"),
1532 g_strerror (buf[1]));
1538 G_SPAWN_ERROR_FAILED,
1539 _("Unknown error executing child process \"%s\""),
1544 goto cleanup_and_fail;
1547 /* Get child pid from intermediate child pipe. */
1548 if (intermediate_child)
1552 if (!read_ints (child_pid_report_pipe[0],
1553 buf, 1, &n_ints, error))
1554 goto cleanup_and_fail;
1562 G_SPAWN_ERROR_FAILED,
1563 _("Failed to read enough data from child pid pipe (%s)"),
1564 g_strerror (errsv));
1565 goto cleanup_and_fail;
1569 /* we have the child pid */
1574 /* Success against all odds! return the information */
1575 close_and_invalidate (&child_err_report_pipe[0]);
1576 close_and_invalidate (&child_pid_report_pipe[0]);
1582 *standard_input = stdin_pipe[1];
1583 if (standard_output)
1584 *standard_output = stdout_pipe[0];
1586 *standard_error = stderr_pipe[0];
1593 /* There was an error from the Child, reap the child to avoid it being
1600 if (waitpid (pid, NULL, 0) < 0)
1604 else if (errno == ECHILD)
1605 ; /* do nothing, child already reaped */
1607 g_warning ("waitpid() should not fail in "
1608 "'fork_exec_with_pipes'");
1612 close_and_invalidate (&child_err_report_pipe[0]);
1613 close_and_invalidate (&child_err_report_pipe[1]);
1614 close_and_invalidate (&child_pid_report_pipe[0]);
1615 close_and_invalidate (&child_pid_report_pipe[1]);
1616 close_and_invalidate (&stdin_pipe[0]);
1617 close_and_invalidate (&stdin_pipe[1]);
1618 close_and_invalidate (&stdout_pipe[0]);
1619 close_and_invalidate (&stdout_pipe[1]);
1620 close_and_invalidate (&stderr_pipe[0]);
1621 close_and_invalidate (&stderr_pipe[1]);
1627 make_pipe (gint p[2],
1635 G_SPAWN_ERROR_FAILED,
1636 _("Failed to create pipe for communicating with child process (%s)"),
1637 g_strerror (errsv));
1644 /* Based on execvp from GNU C Library */
1647 script_execute (const gchar *file,
1651 /* Count the arguments. */
1656 /* Construct an argument list for the shell. */
1660 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1662 new_argv[0] = (char *) "/bin/sh";
1663 new_argv[1] = (char *) file;
1666 new_argv[argc + 1] = argv[argc];
1670 /* Execute the shell. */
1672 execve (new_argv[0], new_argv, envp);
1674 execv (new_argv[0], new_argv);
1681 my_strchrnul (const gchar *str, gchar c)
1683 gchar *p = (gchar*) str;
1684 while (*p && (*p != c))
1691 g_execute (const gchar *file,
1694 gboolean search_path,
1695 gboolean search_path_from_envp)
1699 /* We check the simple case first. */
1704 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1706 /* Don't search when it contains a slash. */
1708 execve (file, argv, envp);
1712 if (errno == ENOEXEC)
1713 script_execute (file, argv, envp);
1717 gboolean got_eacces = 0;
1718 const gchar *path, *p;
1719 gchar *name, *freeme;
1724 if (search_path_from_envp)
1725 path = g_environ_getenv (envp, "PATH");
1726 if (search_path && path == NULL)
1727 path = g_getenv ("PATH");
1731 /* There is no `PATH' in the environment. The default
1732 * search path in libc is the current directory followed by
1733 * the path `confstr' returns for `_CS_PATH'.
1736 /* In GLib we put . last, for security, and don't use the
1737 * unportable confstr(); UNIX98 does not actually specify
1738 * what to search if PATH is unset. POSIX may, dunno.
1741 path = "/bin:/usr/bin:.";
1744 len = strlen (file) + 1;
1745 pathlen = strlen (path);
1746 freeme = name = g_malloc (pathlen + len + 1);
1748 /* Copy the file name at the top, including '\0' */
1749 memcpy (name + pathlen + 1, file, len);
1750 name = name + pathlen;
1751 /* And add the slash before the filename */
1760 p = my_strchrnul (path, ':');
1763 /* Two adjacent colons, or a colon at the beginning or the end
1764 * of `PATH' means to search the current directory.
1768 startp = memcpy (name - (p - path), path, p - path);
1770 /* Try to execute this name. If it works, execv will not return. */
1772 execve (startp, argv, envp);
1774 execv (startp, argv);
1776 if (errno == ENOEXEC)
1777 script_execute (startp, argv, envp);
1782 /* Record the we got a `Permission denied' error. If we end
1783 * up finding no executable we can use, we want to diagnose
1784 * that we did find one but were denied access.
1797 /* Those errors indicate the file is missing or not executable
1798 * by us, in which case we want to just try the next path
1805 /* Some strange filesystems like AFS return even
1806 * stranger error numbers. They cannot reasonably mean anything
1807 * else so ignore those, too.
1812 /* Some other error means we found an executable file, but
1813 * something went wrong executing it; return the error to our
1820 while (*p++ != '\0');
1822 /* We tried every element and none of them worked. */
1824 /* At least one failure was due to permissions, so report that
1832 /* Return the error from the last attempt (probably ENOENT). */
1837 * g_spawn_close_pid:
1838 * @pid: The process reference to close
1840 * On some platforms, notably Windows, the #GPid type represents a resource
1841 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1842 * is provided for this purpose. It should be used on all platforms, even
1843 * though it doesn't do anything under UNIX.
1846 g_spawn_close_pid (GPid pid)