1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2012, 2013 Red Hat, Inc.
4 * Copyright © 2012, 2013 Canonical Limited
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * See the included COPYING file for more information.
13 * Authors: Colin Walters <walters@verbum.org>
14 * Ryan Lortie <desrt@desrt.ca>
20 * @short_description: Child processes
22 * @see_also: #GSubprocessLauncher
24 * #GSubprocess allows the creation of and interaction with child
27 * Processes can be communicated with using standard GIO-style APIs (ie:
28 * #GInputStream, #GOutputStream). There are GIO-style APIs to wait for
29 * process termination (ie: cancellable and with an asynchronous
32 * There is an API to force a process to terminate, as well as a
33 * race-free API for sending UNIX signals to a subprocess.
35 * One major advantage that GIO brings over the core GLib library is
36 * comprehensive API for asynchronous I/O, such
37 * g_output_stream_splice_async(). This makes GSubprocess
38 * significantly more powerful and flexible than equivalent APIs in
39 * some other languages such as the `subprocess.py`
40 * included with Python. For example, using #GSubprocess one could
41 * create two child processes, reading standard output from the first,
42 * processing it, and writing to the input stream of the second, all
43 * without blocking the main loop.
45 * A powerful g_subprocess_communicate() API is provided similar to the
46 * `communicate()` method of `subprocess.py`. This enables very easy
47 * interaction with a subprocess that has been opened with pipes.
49 * #GSubprocess defaults to tight control over the file descriptors open
50 * in the child process, avoiding dangling-fd issues that are caused by
51 * a simple fork()/exec(). The only open file descriptors in the
52 * spawned process are ones that were explicitly specified by the
53 * #GSubprocess API (unless %G_SUBPROCESS_FLAGS_INHERIT_FDS was
56 * #GSubprocess will quickly reap all child processes as they exit,
57 * avoiding "zombie processes" remaining around for long periods of
58 * time. g_subprocess_wait() can be used to wait for this to happen,
59 * but it will happen even without the call being explicitly made.
61 * As a matter of principle, #GSubprocess has no API that accepts
62 * shell-style space-separated strings. It will, however, match the
63 * typical shell behaviour of searching the PATH for executables that do
64 * not contain a directory separator in their name.
66 * #GSubprocess attempts to have a very simple API for most uses (ie:
67 * spawning a subprocess with arguments and support for most typical
68 * kinds of input and output redirection). See g_subprocess_new(). The
69 * #GSubprocessLauncher API is provided for more complicated cases
70 * (advanced types of redirection, environment variable manipulation,
71 * change of working directory, child setup functions, etc).
73 * A typical use of #GSubprocess will involve calling
74 * g_subprocess_new(), followed by g_subprocess_wait_async() or
75 * g_subprocess_wait(). After the process exits, the status can be
76 * checked using functions such as g_subprocess_get_if_exited() (which
77 * are similar to the familiar WIFEXITED-style POSIX macros).
84 #include "gsubprocess.h"
85 #include "gsubprocesslauncher-private.h"
86 #include "gasyncresult.h"
87 #include "giostream.h"
88 #include "gmemoryinputstream.h"
90 #include "glib-private.h"
94 #include <gio/gunixoutputstream.h>
95 #include <gio/gfiledescriptorbased.h>
96 #include <gio/gunixinputstream.h>
98 #include <glib-unix.h>
104 #include "giowin32-priv.h"
114 #define HAVE_O_CLOEXEC 1
117 #define COMMUNICATE_READ_SIZE 4096
119 /* A GSubprocess can have two possible states: running and not.
121 * These two states are reflected by the value of 'pid'. If it is
122 * non-zero then the process is running, with that pid.
124 * When a GSubprocess is first created with g_object_new() it is not
125 * running. When it is finalized, it is also not running.
127 * During initable_init(), if the g_spawn() is successful then we
128 * immediately register a child watch and take an extra ref on the
129 * subprocess. That reference doesn't drop until the child has quit,
130 * which is why finalize can only happen in the non-running state. In
131 * the event that the g_spawn() failed we will still be finalizing a
132 * non-running GSubprocess (before returning from g_subprocess_new())
135 * We make extensive use of the glib worker thread to guarantee
136 * race-free operation. As with all child watches, glib calls waitpid()
137 * in the worker thread. It reports the child exiting to us via the
138 * worker thread (which means that we can do synchronous waits without
139 * running a separate loop). We also send signals to the child process
140 * via the worker thread so that we don't race with waitpid() and
141 * accidentally send a signal to an already-reaped child.
143 static void initable_iface_init (GInitableIface *initable_iface);
145 typedef GObjectClass GSubprocessClass;
151 /* only used during construction */
152 GSubprocessLauncher *launcher;
153 GSubprocessFlags flags;
156 /* state tracking variables */
157 gchar identifier[24];
162 GMutex pending_waits_lock;
163 GSList *pending_waits;
165 /* These are the streams created if a pipe is requested via flags. */
166 GOutputStream *stdin_pipe;
167 GInputStream *stdout_pipe;
168 GInputStream *stderr_pipe;
171 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
172 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))
186 GSpawnChildSetupFunc child_setup_func;
187 gpointer child_setup_data;
188 GArray *basic_fd_assignments;
189 GArray *needdup_fd_assignments;
193 unset_cloexec (int fd)
198 flags = fcntl (fd, F_GETFD, 0);
203 flags &= (~FD_CLOEXEC);
206 result = fcntl (fd, F_SETFD, flags);
209 while (result == -1 && errsv == EINTR);
214 dupfd_cloexec (int parent_fd)
217 #ifdef F_DUPFD_CLOEXEC
220 fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
223 while (fd == -1 && errsv == EINTR);
225 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
226 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
231 fd = fcntl (parent_fd, F_DUPFD, 3);
234 while (fd == -1 && errsv == EINTR);
235 flags = fcntl (fd, F_GETFD, 0);
241 result = fcntl (fd, F_SETFD, flags);
244 while (result == -1 && errsv == EINTR);
251 * Based on code derived from
252 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
253 * used under the LGPLv2+ with permission from author.
256 child_setup (gpointer user_data)
258 ChildData *child_data = user_data;
263 /* We're on the child side now. "Rename" the file descriptors in
264 * child_data.fds[] to stdin/stdout/stderr.
266 * We don't close the originals. It's possible that the originals
267 * should not be closed and if they should be closed then they should
268 * have been created O_CLOEXEC.
270 for (i = 0; i < 3; i++)
271 if (child_data->fds[i] != -1 && child_data->fds[i] != i)
275 result = dup2 (child_data->fds[i], i);
278 while (result == -1 && errsv == EINTR);
281 /* Basic fd assignments we can just unset FD_CLOEXEC */
282 if (child_data->basic_fd_assignments)
284 for (i = 0; i < child_data->basic_fd_assignments->len; i++)
286 gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
292 /* If we're doing remapping fd assignments, we need to handle
293 * the case where the user has specified e.g.:
296 * We do this by duping the source fds temporarily.
298 if (child_data->needdup_fd_assignments)
300 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
302 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
305 new_parent_fd = dupfd_cloexec (parent_fd);
307 g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
309 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
311 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
312 gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
314 if (parent_fd == child_fd)
316 unset_cloexec (parent_fd);
322 result = dup2 (parent_fd, child_fd);
325 while (result == -1 && errsv == EINTR);
326 (void) close (parent_fd);
331 if (child_data->child_setup_func)
332 child_data->child_setup_func (child_data->child_setup_data);
336 static GInputStream *
337 platform_input_stream_from_spawn_fd (gint fd)
343 return g_unix_input_stream_new (fd, TRUE);
345 return g_win32_input_stream_new_from_fd (fd, TRUE);
349 static GOutputStream *
350 platform_output_stream_from_spawn_fd (gint fd)
356 return g_unix_output_stream_new (fd, TRUE);
358 return g_win32_output_stream_new_from_fd (fd, TRUE);
364 unix_open_file (const char *filename,
370 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
372 /* If we return -1 we should also set the error */
375 gint saved_errno = errno;
378 display_name = g_filename_display_name (filename);
379 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
380 _("Error opening file “%s”: %s"), display_name,
381 g_strerror (saved_errno));
382 g_free (display_name);
383 /* fall through... */
385 #ifndef HAVE_O_CLOEXEC
387 fcntl (my_fd, F_SETFD, FD_CLOEXEC);
395 g_subprocess_set_property (GObject *object,
400 GSubprocess *self = G_SUBPROCESS (object);
405 self->flags = g_value_get_flags (value);
409 self->argv = g_value_dup_boxed (value);
413 g_assert_not_reached ();
418 g_subprocess_exited (GPid pid,
422 GSubprocess *self = user_data;
425 g_assert (self->pid == pid);
427 g_mutex_lock (&self->pending_waits_lock);
428 self->status = status;
429 tasks = self->pending_waits;
430 self->pending_waits = NULL;
432 g_mutex_unlock (&self->pending_waits_lock);
434 /* Signal anyone in g_subprocess_wait_async() to wake up now */
437 g_task_return_boolean (tasks->data, TRUE);
438 g_object_unref (tasks->data);
439 tasks = g_slist_delete_link (tasks, tasks);
442 g_spawn_close_pid (pid);
448 initable_init (GInitable *initable,
449 GCancellable *cancellable,
452 GSubprocess *self = G_SUBPROCESS (initable);
454 ChildData child_data = { { -1, -1, -1 }, 0 };
456 gint *pipe_ptrs[3] = { NULL, NULL, NULL };
457 gint pipe_fds[3] = { -1, -1, -1 };
458 gint close_fds[3] = { -1, -1, -1 };
459 GSpawnFlags spawn_flags = 0;
460 gboolean success = FALSE;
463 /* this is a programmer error */
464 if (!self->argv || !self->argv[0] || !self->argv[0][0])
467 if (g_cancellable_set_error_if_cancelled (cancellable, error))
470 /* We must setup the three fds that will end up in the child as stdin,
475 if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
476 spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
477 else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
478 pipe_ptrs[0] = &pipe_fds[0];
480 else if (self->launcher)
482 if (self->launcher->stdin_fd != -1)
483 child_data.fds[0] = self->launcher->stdin_fd;
484 else if (self->launcher->stdin_path != NULL)
486 child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
487 if (child_data.fds[0] == -1)
494 if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
495 spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
496 else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
497 pipe_ptrs[1] = &pipe_fds[1];
499 else if (self->launcher)
501 if (self->launcher->stdout_fd != -1)
502 child_data.fds[1] = self->launcher->stdout_fd;
503 else if (self->launcher->stdout_path != NULL)
505 child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
506 if (child_data.fds[1] == -1)
512 /* Finally, stderr. */
513 if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
514 spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
515 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
516 pipe_ptrs[2] = &pipe_fds[2];
518 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
519 /* This will work because stderr gets setup after stdout. */
520 child_data.fds[2] = 1;
521 else if (self->launcher)
523 if (self->launcher->stderr_fd != -1)
524 child_data.fds[2] = self->launcher->stderr_fd;
525 else if (self->launcher->stderr_path != NULL)
527 child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
528 if (child_data.fds[2] == -1)
537 child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
538 child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
542 /* argv0 has no '/' in it? We better do a PATH lookup. */
543 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
545 if (self->launcher && self->launcher->path_from_envp)
546 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
548 spawn_flags |= G_SPAWN_SEARCH_PATH;
551 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
552 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
554 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
555 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
558 child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
559 child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
562 success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
564 self->launcher ? self->launcher->envp : NULL,
567 child_setup, &child_data,
572 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
574 g_assert (success == (self->pid != 0));
581 identifier = (guint64) GetProcessId (self->pid);
583 identifier = (guint64) self->pid;
586 s = g_snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
587 g_assert (0 < s && s < sizeof self->identifier);
590 /* Start attempting to reap the child immediately */
593 GMainContext *worker_context;
596 worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
597 source = g_child_watch_source_new (self->pid);
598 g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
599 g_source_attach (source, worker_context);
600 g_source_unref (source);
606 /* we don't need this past init... */
607 self->launcher = NULL;
609 for (i = 0; i < 3; i++)
610 if (close_fds[i] != -1)
611 close (close_fds[i]);
613 self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
614 self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
615 self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
621 g_subprocess_finalize (GObject *object)
623 GSubprocess *self = G_SUBPROCESS (object);
625 g_assert (self->pending_waits == NULL);
626 g_assert (self->pid == 0);
628 g_clear_object (&self->stdin_pipe);
629 g_clear_object (&self->stdout_pipe);
630 g_clear_object (&self->stderr_pipe);
631 g_strfreev (self->argv);
633 g_mutex_clear (&self->pending_waits_lock);
635 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
639 g_subprocess_init (GSubprocess *self)
641 g_mutex_init (&self->pending_waits_lock);
645 initable_iface_init (GInitableIface *initable_iface)
647 initable_iface->init = initable_init;
651 g_subprocess_class_init (GSubprocessClass *class)
653 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
655 gobject_class->finalize = g_subprocess_finalize;
656 gobject_class->set_property = g_subprocess_set_property;
658 g_object_class_install_property (gobject_class, PROP_FLAGS,
659 g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
660 G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
661 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
662 g_object_class_install_property (gobject_class, PROP_ARGV,
663 g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
664 G_TYPE_STRV, G_PARAM_WRITABLE |
665 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
669 * g_subprocess_new: (skip)
670 * @flags: flags that define the behaviour of the subprocess
671 * @error: (nullable): return location for an error, or %NULL
672 * @argv0: first commandline argument to pass to the subprocess
673 * @...: more commandline arguments, followed by %NULL
675 * Create a new process with the given flags and varargs argument
676 * list. By default, matching the g_spawn_async() defaults, the
677 * child's stdin will be set to the system null device, and
678 * stdout/stderr will be inherited from the parent. You can use
679 * @flags to control this behavior.
681 * The argument list must be terminated with %NULL.
683 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
689 g_subprocess_new (GSubprocessFlags flags,
699 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
700 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
702 args = g_ptr_array_new ();
704 va_start (ap, argv0);
705 g_ptr_array_add (args, (gchar *) argv0);
706 while ((arg = va_arg (ap, const gchar *)))
707 g_ptr_array_add (args, (gchar *) arg);
708 g_ptr_array_add (args, NULL);
711 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
713 g_ptr_array_free (args, TRUE);
719 * g_subprocess_newv: (rename-to g_subprocess_new)
720 * @argv: (array zero-terminated=1) (element-type filename): commandline arguments for the subprocess
721 * @flags: flags that define the behaviour of the subprocess
722 * @error: (nullable): return location for an error, or %NULL
724 * Create a new process with the given flags and argument list.
726 * The argument list is expected to be %NULL-terminated.
728 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
734 g_subprocess_newv (const gchar * const *argv,
735 GSubprocessFlags flags,
738 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
740 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
747 * g_subprocess_get_identifier:
748 * @subprocess: a #GSubprocess
750 * On UNIX, returns the process ID as a decimal string.
751 * On Windows, returns the result of GetProcessId() also as a string.
754 g_subprocess_get_identifier (GSubprocess *subprocess)
756 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
759 return subprocess->identifier;
765 * g_subprocess_get_stdin_pipe:
766 * @subprocess: a #GSubprocess
768 * Gets the #GOutputStream that you can write to in order to give data
769 * to the stdin of @subprocess.
771 * The process must have been created with
772 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
774 * Returns: (transfer none): the stdout pipe
779 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
781 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
782 g_return_val_if_fail (subprocess->stdin_pipe, NULL);
784 return subprocess->stdin_pipe;
788 * g_subprocess_get_stdout_pipe:
789 * @subprocess: a #GSubprocess
791 * Gets the #GInputStream from which to read the stdout output of
794 * The process must have been created with
795 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
797 * Returns: (transfer none): the stdout pipe
802 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
804 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
805 g_return_val_if_fail (subprocess->stdout_pipe, NULL);
807 return subprocess->stdout_pipe;
811 * g_subprocess_get_stderr_pipe:
812 * @subprocess: a #GSubprocess
814 * Gets the #GInputStream from which to read the stderr output of
817 * The process must have been created with
818 * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
820 * Returns: (transfer none): the stderr pipe
825 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
827 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
828 g_return_val_if_fail (subprocess->stderr_pipe, NULL);
830 return subprocess->stderr_pipe;
833 /* Remove the first list element containing @data, and return %TRUE. If no
834 * such element is found, return %FALSE. */
836 slist_remove_if_present (GSList **list,
841 for (l = *list, prev = NULL; l != NULL; prev = l, l = prev->next)
846 prev->next = l->next;
860 g_subprocess_wait_cancelled (GCancellable *cancellable,
863 GTask *task = user_data;
865 gboolean task_was_pending;
867 self = g_task_get_source_object (task);
869 g_mutex_lock (&self->pending_waits_lock);
870 task_was_pending = slist_remove_if_present (&self->pending_waits, task);
871 g_mutex_unlock (&self->pending_waits_lock);
873 if (task_was_pending)
875 g_task_return_boolean (task, FALSE);
876 g_object_unref (task); /* ref from pending_waits */
881 * g_subprocess_wait_async:
882 * @subprocess: a #GSubprocess
883 * @cancellable: a #GCancellable, or %NULL
884 * @callback: a #GAsyncReadyCallback to call when the operation is complete
885 * @user_data: user_data for @callback
887 * Wait for the subprocess to terminate.
889 * This is the asynchronous version of g_subprocess_wait().
894 g_subprocess_wait_async (GSubprocess *subprocess,
895 GCancellable *cancellable,
896 GAsyncReadyCallback callback,
901 task = g_task_new (subprocess, cancellable, callback, user_data);
902 g_task_set_source_tag (task, g_subprocess_wait_async);
904 g_mutex_lock (&subprocess->pending_waits_lock);
907 /* Only bother with cancellable if we're putting it in the list.
908 * If not, it's going to dispatch immediately anyway and we will
909 * see the cancellation in the _finish().
912 g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
914 subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
917 g_mutex_unlock (&subprocess->pending_waits_lock);
919 /* If we still have task then it's because did_exit is already TRUE */
922 g_task_return_boolean (task, TRUE);
923 g_object_unref (task);
928 * g_subprocess_wait_finish:
929 * @subprocess: a #GSubprocess
930 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
931 * @error: a pointer to a %NULL #GError, or %NULL
933 * Collects the result of a previous call to
934 * g_subprocess_wait_async().
936 * Returns: %TRUE if successful, or %FALSE with @error set
941 g_subprocess_wait_finish (GSubprocess *subprocess,
942 GAsyncResult *result,
945 return g_task_propagate_boolean (G_TASK (result), error);
948 /* Some generic helpers for emulating synchronous operations using async
952 g_subprocess_sync_setup (void)
954 g_main_context_push_thread_default (g_main_context_new ());
958 g_subprocess_sync_done (GObject *source_object,
959 GAsyncResult *result,
962 GAsyncResult **result_ptr = user_data;
964 *result_ptr = g_object_ref (result);
968 g_subprocess_sync_complete (GAsyncResult **result)
970 GMainContext *context = g_main_context_get_thread_default ();
973 g_main_context_iteration (context, TRUE);
975 g_main_context_pop_thread_default (context);
976 g_main_context_unref (context);
981 * @subprocess: a #GSubprocess
982 * @cancellable: a #GCancellable
985 * Synchronously wait for the subprocess to terminate.
987 * After the process terminates you can query its exit status with
988 * functions such as g_subprocess_get_if_exited() and
989 * g_subprocess_get_exit_status().
991 * This function does not fail in the case of the subprocess having
992 * abnormal termination. See g_subprocess_wait_check() for that.
994 * Cancelling @cancellable doesn't kill the subprocess. Call
995 * g_subprocess_force_exit() if it is desirable.
997 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
1002 g_subprocess_wait (GSubprocess *subprocess,
1003 GCancellable *cancellable,
1006 GAsyncResult *result = NULL;
1009 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1011 /* Synchronous waits are actually the 'more difficult' case because we
1012 * need to deal with the possibility of cancellation. That more or
1013 * less implies that we need a main context (to dispatch either of the
1014 * possible reasons for the operation ending).
1016 * So we make one and then do this async...
1019 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1022 /* We can shortcut in the case that the process already quit (but only
1023 * after we checked the cancellable).
1025 if (subprocess->pid == 0)
1028 /* Otherwise, we need to do this the long way... */
1029 g_subprocess_sync_setup ();
1030 g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
1031 g_subprocess_sync_complete (&result);
1032 success = g_subprocess_wait_finish (subprocess, result, error);
1033 g_object_unref (result);
1039 * g_subprocess_wait_check:
1040 * @subprocess: a #GSubprocess
1041 * @cancellable: a #GCancellable
1044 * Combines g_subprocess_wait() with g_spawn_check_exit_status().
1046 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
1047 * @cancellable was cancelled
1052 g_subprocess_wait_check (GSubprocess *subprocess,
1053 GCancellable *cancellable,
1056 return g_subprocess_wait (subprocess, cancellable, error) &&
1057 g_spawn_check_exit_status (subprocess->status, error);
1061 * g_subprocess_wait_check_async:
1062 * @subprocess: a #GSubprocess
1063 * @cancellable: a #GCancellable, or %NULL
1064 * @callback: a #GAsyncReadyCallback to call when the operation is complete
1065 * @user_data: user_data for @callback
1067 * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
1069 * This is the asynchronous version of g_subprocess_wait_check().
1074 g_subprocess_wait_check_async (GSubprocess *subprocess,
1075 GCancellable *cancellable,
1076 GAsyncReadyCallback callback,
1079 g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
1083 * g_subprocess_wait_check_finish:
1084 * @subprocess: a #GSubprocess
1085 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
1086 * @error: a pointer to a %NULL #GError, or %NULL
1088 * Collects the result of a previous call to
1089 * g_subprocess_wait_check_async().
1091 * Returns: %TRUE if successful, or %FALSE with @error set
1096 g_subprocess_wait_check_finish (GSubprocess *subprocess,
1097 GAsyncResult *result,
1100 return g_subprocess_wait_finish (subprocess, result, error) &&
1101 g_spawn_check_exit_status (subprocess->status, error);
1107 GSubprocess *subprocess;
1112 g_subprocess_actually_send_signal (gpointer user_data)
1114 SignalRecord *signal_record = user_data;
1116 /* The pid is set to zero from the worker thread as well, so we don't
1117 * need to take a lock in order to prevent it from changing under us.
1119 if (signal_record->subprocess->pid)
1120 kill (signal_record->subprocess->pid, signal_record->signalnum);
1122 g_object_unref (signal_record->subprocess);
1124 g_slice_free (SignalRecord, signal_record);
1130 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1133 SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1135 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1137 /* This MUST be a lower priority than the priority that the child
1138 * watch source uses in initable_init().
1140 * Reaping processes, reporting the results back to GSubprocess and
1141 * sending signals is all done in the glib worker thread. We cannot
1142 * have a kill() done after the reap and before the report without
1143 * risking killing a process that's no longer there so the kill()
1144 * needs to have the lower priority.
1146 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1148 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1149 G_PRIORITY_HIGH_IDLE,
1150 g_subprocess_actually_send_signal,
1151 g_slice_dup (SignalRecord, &signal_record),
1156 * g_subprocess_send_signal:
1157 * @subprocess: a #GSubprocess
1158 * @signal_num: the signal number to send
1160 * Sends the UNIX signal @signal_num to the subprocess, if it is still
1163 * This API is race-free. If the subprocess has terminated, it will not
1166 * This API is not available on Windows.
1171 g_subprocess_send_signal (GSubprocess *subprocess,
1174 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1176 g_subprocess_dispatch_signal (subprocess, signal_num);
1181 * g_subprocess_force_exit:
1182 * @subprocess: a #GSubprocess
1184 * Use an operating-system specific method to attempt an immediate,
1185 * forceful termination of the process. There is no mechanism to
1186 * determine whether or not the request itself was successful;
1187 * however, you can use g_subprocess_wait() to monitor the status of
1188 * the process after calling this function.
1190 * On Unix, this function sends %SIGKILL.
1195 g_subprocess_force_exit (GSubprocess *subprocess)
1197 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1200 g_subprocess_dispatch_signal (subprocess, SIGKILL);
1202 TerminateProcess (subprocess->pid, 1);
1207 * g_subprocess_get_status:
1208 * @subprocess: a #GSubprocess
1210 * Gets the raw status code of the process, as from waitpid().
1212 * This value has no particular meaning, but it can be used with the
1213 * macros defined by the system headers such as WIFEXITED. It can also
1214 * be used with g_spawn_check_exit_status().
1216 * It is more likely that you want to use g_subprocess_get_if_exited()
1217 * followed by g_subprocess_get_exit_status().
1219 * It is an error to call this function before g_subprocess_wait() has
1222 * Returns: the (meaningless) waitpid() exit status from the kernel
1227 g_subprocess_get_status (GSubprocess *subprocess)
1229 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1230 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1232 return subprocess->status;
1236 * g_subprocess_get_successful:
1237 * @subprocess: a #GSubprocess
1239 * Checks if the process was "successful". A process is considered
1240 * successful if it exited cleanly with an exit status of 0, either by
1241 * way of the exit() system call or return from main().
1243 * It is an error to call this function before g_subprocess_wait() has
1246 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1251 g_subprocess_get_successful (GSubprocess *subprocess)
1253 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1254 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1257 return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1259 return subprocess->status == 0;
1264 * g_subprocess_get_if_exited:
1265 * @subprocess: a #GSubprocess
1267 * Check if the given subprocess exited normally (ie: by way of exit()
1268 * or return from main()).
1270 * This is equivalent to the system WIFEXITED macro.
1272 * It is an error to call this function before g_subprocess_wait() has
1275 * Returns: %TRUE if the case of a normal exit
1280 g_subprocess_get_if_exited (GSubprocess *subprocess)
1282 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1283 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1286 return WIFEXITED (subprocess->status);
1293 * g_subprocess_get_exit_status:
1294 * @subprocess: a #GSubprocess
1296 * Check the exit status of the subprocess, given that it exited
1297 * normally. This is the value passed to the exit() system call or the
1298 * return value from main.
1300 * This is equivalent to the system WEXITSTATUS macro.
1302 * It is an error to call this function before g_subprocess_wait() and
1303 * unless g_subprocess_get_if_exited() returned %TRUE.
1305 * Returns: the exit status
1310 g_subprocess_get_exit_status (GSubprocess *subprocess)
1312 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1313 g_return_val_if_fail (subprocess->pid == 0, 1);
1316 g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1318 return WEXITSTATUS (subprocess->status);
1320 return subprocess->status;
1325 * g_subprocess_get_if_signaled:
1326 * @subprocess: a #GSubprocess
1328 * Check if the given subprocess terminated in response to a signal.
1330 * This is equivalent to the system WIFSIGNALED macro.
1332 * It is an error to call this function before g_subprocess_wait() has
1335 * Returns: %TRUE if the case of termination due to a signal
1340 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1342 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1343 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1346 return WIFSIGNALED (subprocess->status);
1353 * g_subprocess_get_term_sig:
1354 * @subprocess: a #GSubprocess
1356 * Get the signal number that caused the subprocess to terminate, given
1357 * that it terminated due to a signal.
1359 * This is equivalent to the system WTERMSIG macro.
1361 * It is an error to call this function before g_subprocess_wait() and
1362 * unless g_subprocess_get_if_signaled() returned %TRUE.
1364 * Returns: the signal causing termination
1369 g_subprocess_get_term_sig (GSubprocess *subprocess)
1371 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1372 g_return_val_if_fail (subprocess->pid == 0, 0);
1375 g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1377 return WTERMSIG (subprocess->status);
1379 g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1380 "g_subprocess_get_if_signaled() always returns FALSE...");
1387 g_subprocess_set_launcher (GSubprocess *subprocess,
1388 GSubprocessLauncher *launcher)
1390 subprocess->launcher = launcher;
1394 /* g_subprocess_communicate implementation below:
1396 * This is a tough problem. We have to watch 5 things at the same time:
1398 * - writing to stdin made progress
1399 * - reading from stdout made progress
1400 * - reading from stderr made progress
1401 * - process terminated
1402 * - cancellable being cancelled by caller
1404 * We use a GMainContext for all of these (either as async function
1405 * calls or as a GSource (in the case of the cancellable). That way at
1406 * least we don't have to worry about threading.
1408 * For the sync case we use the usual trick of creating a private main
1409 * context and iterating it until completion.
1411 * It's very possible that the process will dump a lot of data to stdout
1412 * just before it quits, so we can easily have data to read from stdout
1413 * and see the process has terminated at the same time. We want to make
1414 * sure that we read all of the data from the pipes first, though, so we
1415 * do IO operations at a higher priority than the wait operation (which
1416 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1417 * multiple reads to get this data, the pipe() will always be polling
1418 * as ready and with the async result for the read at a higher priority,
1419 * the main context will not dispatch the completion for the wait().
1421 * We keep our own private GCancellable. In the event that any of the
1422 * above suffers from an error condition (including the user cancelling
1423 * their cancellable) we immediately dispatch the GTask with the error
1424 * result and fire our cancellable to cleanup any pending operations.
1425 * In the case that the error is that the user's cancellable was fired,
1426 * it's vaguely wasteful to report an error because GTask will handle
1427 * this automatically, so we just return FALSE.
1429 * We let each pending sub-operation take a ref on the GTask of the
1430 * communicate operation. We have to be careful that we don't report
1431 * the task completion more than once, though, so we keep a flag for
1436 const gchar *stdin_data;
1442 GInputStream *stdin_buf;
1443 GMemoryOutputStream *stdout_buf;
1444 GMemoryOutputStream *stderr_buf;
1446 GCancellable *cancellable;
1447 GSource *cancellable_source;
1449 guint outstanding_ops;
1450 gboolean reported_error;
1454 g_subprocess_communicate_made_progress (GObject *source_object,
1455 GAsyncResult *result,
1458 CommunicateState *state;
1459 GSubprocess *subprocess;
1460 GError *error = NULL;
1464 g_assert (source_object != NULL);
1467 subprocess = g_task_get_source_object (task);
1468 state = g_task_get_task_data (task);
1469 source = source_object;
1471 state->outstanding_ops--;
1473 if (source == subprocess->stdin_pipe ||
1474 source == state->stdout_buf ||
1475 source == state->stderr_buf)
1477 if (g_output_stream_splice_finish ((GOutputStream*) source, result, &error) == -1)
1480 if (source == state->stdout_buf ||
1481 source == state->stderr_buf)
1483 /* This is a memory stream, so it can't be cancelled or return
1488 gsize bytes_written;
1489 if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1493 if (!g_output_stream_close (source, NULL, &error))
1497 else if (source == subprocess)
1499 (void) g_subprocess_wait_finish (subprocess, result, &error);
1502 g_assert_not_reached ();
1507 /* Only report the first error we see.
1509 * We might be seeing an error as a result of the cancellation
1510 * done when the process quits.
1512 if (!state->reported_error)
1514 state->reported_error = TRUE;
1515 g_cancellable_cancel (state->cancellable);
1516 g_task_return_error (task, error);
1519 g_error_free (error);
1521 else if (state->outstanding_ops == 0)
1523 g_task_return_boolean (task, TRUE);
1526 /* And drop the original ref */
1527 g_object_unref (task);
1531 g_subprocess_communicate_cancelled (GCancellable *cancellable,
1534 CommunicateState *state = user_data;
1536 g_cancellable_cancel (state->cancellable);
1542 g_subprocess_communicate_state_free (gpointer data)
1544 CommunicateState *state = data;
1546 g_clear_object (&state->cancellable);
1547 g_clear_object (&state->stdin_buf);
1548 g_clear_object (&state->stdout_buf);
1549 g_clear_object (&state->stderr_buf);
1551 if (state->cancellable_source)
1553 g_source_destroy (state->cancellable_source);
1554 g_source_unref (state->cancellable_source);
1557 g_slice_free (CommunicateState, state);
1560 static CommunicateState *
1561 g_subprocess_communicate_internal (GSubprocess *subprocess,
1564 GCancellable *cancellable,
1565 GAsyncReadyCallback callback,
1568 CommunicateState *state;
1571 task = g_task_new (subprocess, cancellable, callback, user_data);
1572 g_task_set_source_tag (task, g_subprocess_communicate_internal);
1574 state = g_slice_new0 (CommunicateState);
1575 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1577 state->cancellable = g_cancellable_new ();
1578 state->add_nul = add_nul;
1582 state->cancellable_source = g_cancellable_source_new (cancellable);
1583 /* No ref held here, but we unref the source from state's free function */
1584 g_source_set_callback (state->cancellable_source,
1585 G_SOURCE_FUNC (g_subprocess_communicate_cancelled),
1587 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1590 if (subprocess->stdin_pipe)
1592 g_assert (stdin_buf != NULL);
1593 state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1594 g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1595 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1596 G_PRIORITY_DEFAULT, state->cancellable,
1597 g_subprocess_communicate_made_progress, g_object_ref (task));
1598 state->outstanding_ops++;
1601 if (subprocess->stdout_pipe)
1603 state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1604 g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1605 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1606 G_PRIORITY_DEFAULT, state->cancellable,
1607 g_subprocess_communicate_made_progress, g_object_ref (task));
1608 state->outstanding_ops++;
1611 if (subprocess->stderr_pipe)
1613 state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1614 g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1615 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1616 G_PRIORITY_DEFAULT, state->cancellable,
1617 g_subprocess_communicate_made_progress, g_object_ref (task));
1618 state->outstanding_ops++;
1621 g_subprocess_wait_async (subprocess, state->cancellable,
1622 g_subprocess_communicate_made_progress, g_object_ref (task));
1623 state->outstanding_ops++;
1625 g_object_unref (task);
1630 * g_subprocess_communicate:
1631 * @subprocess: a #GSubprocess
1632 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1633 * @cancellable: a #GCancellable
1634 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
1635 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
1636 * @error: a pointer to a %NULL #GError pointer, or %NULL
1638 * Communicate with the subprocess until it terminates, and all input
1639 * and output has been completed.
1641 * If @stdin_buf is given, the subprocess must have been created with
1642 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1643 * stdin of the subprocess and the pipe is closed (ie: EOF).
1645 * At the same time (as not to cause blocking when dealing with large
1646 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1647 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1648 * streams. The data that was read is returned in @stdout and/or
1651 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1652 * @stdout_buf will contain the data read from stdout. Otherwise, for
1653 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1654 * @stdout_buf will be set to %NULL. Similar provisions apply to
1655 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1657 * As usual, any output variable may be given as %NULL to ignore it.
1659 * If you desire the stdout and stderr data to be interleaved, create
1660 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1661 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1662 * in @stdout_buf and @stderr_buf will be set to %NULL.
1664 * In case of any error (including cancellation), %FALSE will be
1665 * returned with @error set. Some or all of the stdin data may have
1666 * been written. Any stdout or stderr data that has been read will be
1667 * discarded. None of the out variables (aside from @error) will have
1668 * been set to anything in particular and should not be inspected.
1670 * In the case that %TRUE is returned, the subprocess has exited and the
1671 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1672 * g_subprocess_get_exit_status()) may be used.
1674 * You should not attempt to use any of the subprocess pipes after
1675 * starting this function, since they may be left in strange states,
1676 * even if the operation was cancelled. You should especially not
1677 * attempt to interact with the pipes while the operation is in progress
1678 * (either from another thread or if using the asynchronous version).
1680 * Returns: %TRUE if successful
1685 g_subprocess_communicate (GSubprocess *subprocess,
1687 GCancellable *cancellable,
1688 GBytes **stdout_buf,
1689 GBytes **stderr_buf,
1692 GAsyncResult *result = NULL;
1695 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1696 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1697 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1698 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1700 g_subprocess_sync_setup ();
1701 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1702 g_subprocess_sync_done, &result);
1703 g_subprocess_sync_complete (&result);
1704 success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1705 g_object_unref (result);
1711 * g_subprocess_communicate_async:
1713 * @stdin_buf: (nullable): Input data, or %NULL
1714 * @cancellable: (nullable): Cancellable
1715 * @callback: Callback
1716 * @user_data: User data
1718 * Asynchronous version of g_subprocess_communicate(). Complete
1719 * invocation with g_subprocess_communicate_finish().
1722 g_subprocess_communicate_async (GSubprocess *subprocess,
1724 GCancellable *cancellable,
1725 GAsyncReadyCallback callback,
1728 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1729 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1730 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1732 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1736 * g_subprocess_communicate_finish:
1739 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
1740 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
1743 * Complete an invocation of g_subprocess_communicate_async().
1746 g_subprocess_communicate_finish (GSubprocess *subprocess,
1747 GAsyncResult *result,
1748 GBytes **stdout_buf,
1749 GBytes **stderr_buf,
1753 CommunicateState *state;
1755 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1756 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1757 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1759 g_object_ref (result);
1761 state = g_task_get_task_data ((GTask*)result);
1762 success = g_task_propagate_boolean ((GTask*)result, error);
1767 *stdout_buf = (state->stdout_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stdout_buf) : NULL;
1769 *stderr_buf = (state->stderr_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stderr_buf) : NULL;
1772 g_object_unref (result);
1777 * g_subprocess_communicate_utf8:
1778 * @subprocess: a #GSubprocess
1779 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1780 * @cancellable: a #GCancellable
1781 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
1782 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
1783 * @error: a pointer to a %NULL #GError pointer, or %NULL
1785 * Like g_subprocess_communicate(), but validates the output of the
1786 * process as UTF-8, and returns it as a regular NUL terminated string.
1789 g_subprocess_communicate_utf8 (GSubprocess *subprocess,
1790 const char *stdin_buf,
1791 GCancellable *cancellable,
1796 GAsyncResult *result = NULL;
1798 GBytes *stdin_bytes;
1799 size_t stdin_buf_len = 0;
1801 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1802 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1803 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1804 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1806 if (stdin_buf != NULL)
1807 stdin_buf_len = strlen (stdin_buf);
1808 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1810 g_subprocess_sync_setup ();
1811 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1812 g_subprocess_sync_done, &result);
1813 g_subprocess_sync_complete (&result);
1814 success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1815 g_object_unref (result);
1817 g_bytes_unref (stdin_bytes);
1822 * g_subprocess_communicate_utf8_async:
1824 * @stdin_buf: (nullable): Input data, or %NULL
1825 * @cancellable: Cancellable
1826 * @callback: Callback
1827 * @user_data: User data
1829 * Asynchronous version of g_subprocess_communicate_utf8(). Complete
1830 * invocation with g_subprocess_communicate_utf8_finish().
1833 g_subprocess_communicate_utf8_async (GSubprocess *subprocess,
1834 const char *stdin_buf,
1835 GCancellable *cancellable,
1836 GAsyncReadyCallback callback,
1839 GBytes *stdin_bytes;
1840 size_t stdin_buf_len = 0;
1842 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1843 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1844 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1846 if (stdin_buf != NULL)
1847 stdin_buf_len = strlen (stdin_buf);
1848 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1850 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1852 g_bytes_unref (stdin_bytes);
1856 communicate_result_validate_utf8 (const char *stream_name,
1857 char **return_location,
1858 GMemoryOutputStream *buffer,
1861 if (return_location == NULL)
1867 *return_location = g_memory_output_stream_steal_data (buffer);
1868 if (!g_utf8_validate (*return_location, -1, &end))
1870 g_free (*return_location);
1871 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1872 "Invalid UTF-8 in child %s at offset %lu",
1874 (unsigned long) (end - *return_location));
1879 *return_location = NULL;
1885 * g_subprocess_communicate_utf8_finish:
1888 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
1889 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
1892 * Complete an invocation of g_subprocess_communicate_utf8_async().
1895 g_subprocess_communicate_utf8_finish (GSubprocess *subprocess,
1896 GAsyncResult *result,
1901 gboolean ret = FALSE;
1902 CommunicateState *state;
1904 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1905 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1906 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1908 g_object_ref (result);
1910 state = g_task_get_task_data ((GTask*)result);
1911 if (!g_task_propagate_boolean ((GTask*)result, error))
1914 /* TODO - validate UTF-8 while streaming, rather than all at once.
1916 if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1920 if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1927 g_object_unref (result);