1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2012, 2013 Red Hat, Inc.
4 * Copyright © 2012, 2013 Canonical Limited
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2 of the licence or (at
9 * 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
21 * @see_also: #GSubprocessLauncher
23 * #GSubprocess allows the creation of and interaction with child
26 * Processes can be communicated with using standard GIO-style APIs (ie:
27 * #GInputStream, #GOutputStream). There are GIO-style APIs to wait for
28 * process termination (ie: cancellable and with an asynchronous
31 * There is an API to force a process to terminate, as well as a
32 * race-free API for sending UNIX signals to a subprocess.
34 * One major advantage that GIO brings over the core GLib library is
35 * comprehensive API for asynchronous I/O, such
36 * g_output_stream_splice_async(). This makes GSubprocess
37 * significantly more powerful and flexible than equivalent APIs in
38 * some other languages such as the <literal>subprocess.py</literal>
39 * included with Python. For example, using #GSubprocess one could
40 * create two child processes, reading standard output from the first,
41 * processing it, and writing to the input stream of the second, all
42 * without blocking the main loop.
44 * A powerful g_subprocess_communicate() API is provided similar to the
45 * <literal>communicate()</literal> method of
46 * <literal>subprocess.py</literal>. This enables very easy interaction
47 * 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() or
75 * g_subprocess_wait_sync(). 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"
111 #define COMMUNICATE_READ_SIZE 4096
113 /* A GSubprocess can have two possible states: running and not.
115 * These two states are reflected by the value of 'pid'. If it is
116 * non-zero then the process is running, with that pid.
118 * When a GSubprocess is first created with g_object_new() it is not
119 * running. When it is finalized, it is also not running.
121 * During initable_init(), if the g_spawn() is successful then we
122 * immediately register a child watch and take an extra ref on the
123 * subprocess. That reference doesn't drop until the child has quit,
124 * which is why finalize can only happen in the non-running state. In
125 * the event that the g_spawn() failed we will still be finalizing a
126 * non-running GSubprocess (before returning from g_subprocess_new())
129 * We make extensive use of the glib worker thread to guarantee
130 * race-free operation. As with all child watches, glib calls waitpid()
131 * in the worker thread. It reports the child exiting to us via the
132 * worker thread (which means that we can do synchronous waits without
133 * running a separate loop). We also send signals to the child process
134 * via the worker thread so that we don't race with waitpid() and
135 * accidentally send a signal to an already-reaped child.
137 static void initable_iface_init (GInitableIface *initable_iface);
139 typedef GObjectClass GSubprocessClass;
145 /* only used during construction */
146 GSubprocessLauncher *launcher;
147 GSubprocessFlags flags;
150 /* state tracking variables */
151 gchar identifier[24];
156 GMutex pending_waits_lock;
157 GSList *pending_waits;
159 /* These are the streams created if a pipe is requested via flags. */
160 GOutputStream *stdin_pipe;
161 GInputStream *stdout_pipe;
162 GInputStream *stderr_pipe;
165 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
166 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init));
180 GSpawnChildSetupFunc child_setup_func;
181 gpointer child_setup_data;
182 GArray *basic_fd_assignments;
183 GArray *needdup_fd_assignments;
187 unset_cloexec (int fd)
192 flags = fcntl (fd, F_GETFD, 0);
196 flags &= (~FD_CLOEXEC);
198 result = fcntl (fd, F_SETFD, flags);
199 while (result == -1 && errno == EINTR);
204 dupfd_cloexec (int parent_fd)
207 #ifdef F_DUPFD_CLOEXEC
209 fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
210 while (fd == -1 && errno == EINTR);
212 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
213 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
217 fd = fcntl (parent_fd, F_DUPFD, 3);
218 while (fd == -1 && errno == EINTR);
219 flags = fcntl (fd, F_GETFD, 0);
224 result = fcntl (fd, F_SETFD, flags);
225 while (result == -1 && errno == EINTR);
232 * Based on code derived from
233 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
234 * used under the LGPLv2+ with permission from author.
237 child_setup (gpointer user_data)
239 ChildData *child_data = user_data;
243 /* We're on the child side now. "Rename" the file descriptors in
244 * child_data.fds[] to stdin/stdout/stderr.
246 * We don't close the originals. It's possible that the originals
247 * should not be closed and if they should be closed then they should
248 * have been created O_CLOEXEC.
250 for (i = 0; i < 3; i++)
251 if (child_data->fds[i] != -1 && child_data->fds[i] != i)
254 result = dup2 (child_data->fds[i], i);
255 while (result == -1 && errno == EINTR);
258 /* Basic fd assignments we can just unset FD_CLOEXEC */
259 if (child_data->basic_fd_assignments)
261 for (i = 0; i < child_data->basic_fd_assignments->len; i++)
263 gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
269 /* If we're doing remapping fd assignments, we need to handle
270 * the case where the user has specified e.g.:
273 * We do this by duping the source fds temporarily.
275 if (child_data->needdup_fd_assignments)
277 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
279 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
282 new_parent_fd = dupfd_cloexec (parent_fd);
284 g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
286 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
288 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
289 gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
291 if (parent_fd == child_fd)
293 unset_cloexec (parent_fd);
298 result = dup2 (parent_fd, child_fd);
299 while (result == -1 && errno == EINTR);
300 (void) close (parent_fd);
305 if (child_data->child_setup_func)
306 child_data->child_setup_func (child_data->child_setup_data);
310 static GInputStream *
311 platform_input_stream_from_spawn_fd (gint fd)
317 return g_unix_input_stream_new (fd, TRUE);
319 return g_win32_input_stream_new_from_fd (fd, TRUE);
323 static GOutputStream *
324 platform_output_stream_from_spawn_fd (gint fd)
330 return g_unix_output_stream_new (fd, TRUE);
332 return g_win32_output_stream_new_from_fd (fd, TRUE);
338 unix_open_file (const char *filename,
344 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
346 /* If we return -1 we should also set the error */
349 gint saved_errno = errno;
352 display_name = g_filename_display_name (filename);
353 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
354 _("Error opening file '%s': %s"), display_name,
355 g_strerror (saved_errno));
356 g_free (display_name);
357 /* fall through... */
365 g_subprocess_set_property (GObject *object,
370 GSubprocess *self = G_SUBPROCESS (object);
375 self->flags = g_value_get_flags (value);
379 self->argv = g_value_dup_boxed (value);
383 g_assert_not_reached ();
388 g_subprocess_exited (GPid pid,
392 GSubprocess *self = user_data;
395 g_assert (self->pid == pid);
397 g_mutex_lock (&self->pending_waits_lock);
398 self->status = status;
399 tasks = self->pending_waits;
400 self->pending_waits = NULL;
402 g_mutex_unlock (&self->pending_waits_lock);
404 /* Signal anyone in g_subprocess_wait_async() to wake up now */
407 g_task_return_boolean (tasks->data, TRUE);
408 tasks = g_slist_delete_link (tasks, tasks);
411 g_spawn_close_pid (pid);
417 initable_init (GInitable *initable,
418 GCancellable *cancellable,
421 GSubprocess *self = G_SUBPROCESS (initable);
423 ChildData child_data = { { -1, -1, -1 }, 0 };
425 gint *pipe_ptrs[3] = { NULL, NULL, NULL };
426 gint pipe_fds[3] = { -1, -1, -1 };
427 gint close_fds[3] = { -1, -1, -1 };
428 GSpawnFlags spawn_flags = 0;
429 gboolean success = FALSE;
432 /* this is a programmer error */
433 if (!self->argv || !self->argv[0] || !self->argv[0][0])
436 if (g_cancellable_set_error_if_cancelled (cancellable, error))
439 /* We must setup the three fds that will end up in the child as stdin,
444 if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
445 spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
446 else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
447 pipe_ptrs[0] = &pipe_fds[0];
449 else if (self->launcher)
451 if (self->launcher->stdin_fd != -1)
452 child_data.fds[0] = self->launcher->stdin_fd;
453 else if (self->launcher->stdin_path != NULL)
455 child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
456 if (child_data.fds[0] == -1)
463 if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
464 spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
465 else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
466 pipe_ptrs[1] = &pipe_fds[1];
468 else if (self->launcher)
470 if (self->launcher->stdout_fd != -1)
471 child_data.fds[1] = self->launcher->stdout_fd;
472 else if (self->launcher->stdout_path != NULL)
474 child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
475 if (child_data.fds[1] == -1)
481 /* Finally, stderr. */
482 if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
483 spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
484 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
485 pipe_ptrs[2] = &pipe_fds[2];
487 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
488 /* This will work because stderr gets setup after stdout. */
489 child_data.fds[2] = 1;
490 else if (self->launcher)
492 if (self->launcher->stderr_fd != -1)
493 child_data.fds[2] = self->launcher->stderr_fd;
494 else if (self->launcher->stderr_path != NULL)
496 child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
497 if (child_data.fds[2] == -1)
506 child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
507 child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
511 /* argv0 has no '/' in it? We better do a PATH lookup. */
512 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
514 if (self->launcher && self->launcher->path_from_envp)
515 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
517 spawn_flags |= G_SPAWN_SEARCH_PATH;
520 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
521 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
523 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
524 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
527 child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
528 child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
531 success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
533 self->launcher ? self->launcher->envp : NULL,
536 child_setup, &child_data,
541 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
543 g_assert (success == (self->pid != 0));
550 identifier = (guint64) GetProcessId (self->pid);
552 identifier = (guint64) self->pid;
555 s = snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
556 g_assert (0 < s && s < sizeof self->identifier);
559 /* Start attempting to reap the child immediately */
562 GMainContext *worker_context;
565 worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
566 source = g_child_watch_source_new (self->pid);
567 g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
568 g_source_attach (source, worker_context);
569 g_source_unref (source);
575 /* we don't need this past init... */
576 self->launcher = NULL;
578 for (i = 0; i < 3; i++)
579 if (close_fds[i] != -1)
580 close (close_fds[i]);
582 self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
583 self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
584 self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
590 g_subprocess_finalize (GObject *object)
592 GSubprocess *self = G_SUBPROCESS (object);
594 g_assert (self->pending_waits == NULL);
595 g_assert (self->pid == 0);
597 g_clear_object (&self->stdin_pipe);
598 g_clear_object (&self->stdout_pipe);
599 g_clear_object (&self->stderr_pipe);
602 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
606 g_subprocess_init (GSubprocess *self)
611 initable_iface_init (GInitableIface *initable_iface)
613 initable_iface->init = initable_init;
617 g_subprocess_class_init (GSubprocessClass *class)
619 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
621 gobject_class->finalize = g_subprocess_finalize;
622 gobject_class->set_property = g_subprocess_set_property;
624 g_object_class_install_property (gobject_class, PROP_FLAGS,
625 g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
626 G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
627 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
628 g_object_class_install_property (gobject_class, PROP_ARGV,
629 g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
630 G_TYPE_STRV, G_PARAM_WRITABLE |
631 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
635 * g_subprocess_new: (skip)
636 * @flags: flags that define the behaviour of the subprocess
637 * @error: (allow-none): return location for an error, or %NULL
638 * @argv0: first commandline argument to pass to the subprocess,
639 * followed by more arguments, followed by %NULL
641 * Create a new process with the given flags and varargs argument list.
643 * The argument list must be terminated with %NULL.
645 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
651 g_subprocess_new (GSubprocessFlags flags,
661 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
662 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
664 args = g_ptr_array_new ();
666 va_start (ap, argv0);
667 g_ptr_array_add (args, (gchar *) argv0);
668 while ((arg = va_arg (ap, const gchar *)))
669 g_ptr_array_add (args, (gchar *) arg);
670 g_ptr_array_add (args, NULL);
672 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
674 g_ptr_array_free (args, TRUE);
681 * @argv: commandline arguments for the subprocess
682 * @flags: flags that define the behaviour of the subprocess
683 * @error: (allow-none): return location for an error, or %NULL
685 * Create a new process with the given flags and argument list.
687 * The argument list is expected to be %NULL-terminated.
689 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
693 * Rename to: g_subprocess_new
696 g_subprocess_newv (const gchar * const *argv,
697 GSubprocessFlags flags,
700 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
702 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
709 g_subprocess_get_identifier (GSubprocess *subprocess)
711 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
714 return subprocess->identifier;
720 * g_subprocess_get_stdin_pipe:
721 * @subprocess: a #GSubprocess
723 * Gets the #GOutputStream that you can write to in order to give data
724 * to the stdin of @subprocess.
726 * The process must have been created with
727 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
729 * Returns: the stdout pipe
734 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
736 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
737 g_return_val_if_fail (subprocess->stdin_pipe, NULL);
739 return subprocess->stdin_pipe;
743 * g_subprocess_get_stdout_pipe:
744 * @subprocess: a #GSubprocess
746 * Gets the #GInputStream from which to read the stdout output of
749 * The process must have been created with
750 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
752 * Returns: the stdout pipe
757 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
759 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
760 g_return_val_if_fail (subprocess->stdout_pipe, NULL);
762 return subprocess->stdout_pipe;
766 * g_subprocess_get_stderr_pipe:
767 * @subprocess: a #GSubprocess
769 * Gets the #GInputStream from which to read the stderr output of
772 * The process must have been created with
773 * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
775 * Returns: the stderr pipe
780 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
782 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
783 g_return_val_if_fail (subprocess->stderr_pipe, NULL);
785 return subprocess->stderr_pipe;
789 g_subprocess_wait_cancelled (GCancellable *cancellable,
792 GTask *task = user_data;
795 self = g_task_get_source_object (task);
797 g_mutex_lock (&self->pending_waits_lock);
798 self->pending_waits = g_slist_remove (self->pending_waits, task);
799 g_mutex_unlock (&self->pending_waits_lock);
801 g_task_return_boolean (task, FALSE);
802 g_object_unref (task);
806 * g_subprocess_wait_async:
807 * @subprocess: a #GSubprocess
808 * @cancellable: a #GCancellable, or %NULL
809 * @callback: a #GAsyncReadyCallback to call when the operation is complete
810 * @user_data: user_data for @callback
812 * Wait for the subprocess to terminate.
814 * This is the asynchronous version of g_subprocess_wait().
819 g_subprocess_wait_async (GSubprocess *subprocess,
820 GCancellable *cancellable,
821 GAsyncReadyCallback callback,
826 task = g_task_new (subprocess, cancellable, callback, user_data);
828 g_mutex_lock (&subprocess->pending_waits_lock);
831 /* Only bother with cancellable if we're putting it in the list.
832 * If not, it's going to dispatch immediately anyway and we will
833 * see the cancellation in the _finish().
836 g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
838 subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
841 g_mutex_unlock (&subprocess->pending_waits_lock);
843 /* If we still have task then it's because did_exit is already TRUE */
846 g_task_return_boolean (task, TRUE);
847 g_object_unref (task);
852 * g_subprocess_wait_finish:
853 * @subprocess: a #GSubprocess
854 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
855 * @error: a pointer to a %NULL #GError, or %NULL
857 * Collects the result of a previous call to
858 * g_subprocess_wait_async().
860 * Returns: %TRUE if successful, or %FALSE with @error set
865 g_subprocess_wait_finish (GSubprocess *subprocess,
866 GAsyncResult *result,
869 return g_task_propagate_boolean (G_TASK (result), error);
872 /* Some generic helpers for emulating synchronous operations using async
876 g_subprocess_sync_setup (void)
878 g_main_context_push_thread_default (g_main_context_new ());
882 g_subprocess_sync_done (GObject *source_object,
883 GAsyncResult *result,
886 GAsyncResult **result_ptr = user_data;
888 *result_ptr = g_object_ref (result);
892 g_subprocess_sync_complete (GAsyncResult **result)
894 GMainContext *context = g_main_context_get_thread_default ();
897 g_main_context_iteration (context, TRUE);
899 g_main_context_pop_thread_default (context);
900 g_main_context_unref (context);
905 * @subprocess: a #GSubprocess
906 * @cancellable: a #GCancellable
909 * Synchronously wait for the subprocess to terminate.
911 * After the process terminates you can query its exit status with
912 * functions such as g_subprocess_get_if_exited() and
913 * g_subprocess_get_exit_status().
915 * This function does not fail in the case of the subprocess having
916 * abnormal termination. See g_subprocess_wait_check() for that.
918 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
923 g_subprocess_wait (GSubprocess *subprocess,
924 GCancellable *cancellable,
927 GAsyncResult *result = NULL;
930 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
932 /* Synchronous waits are actually the 'more difficult' case because we
933 * need to deal with the possibility of cancellation. That more or
934 * less implies that we need a main context (to dispatch either of the
935 * possible reasons for the operation ending).
937 * So we make one and then do this async...
940 if (g_cancellable_set_error_if_cancelled (cancellable, error))
943 /* We can shortcut in the case that the process already quit (but only
944 * after we checked the cancellable).
946 if (subprocess->pid == 0)
949 /* Otherwise, we need to do this the long way... */
950 g_subprocess_sync_setup ();
951 g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
952 g_subprocess_sync_complete (&result);
953 success = g_subprocess_wait_finish (subprocess, result, error);
954 g_object_unref (result);
960 * g_subprocess_wait_check:
961 * @subprocess: a #GSubprocess
962 * @cancellable: a #GCancellable
965 * Combines g_subprocess_wait() with g_spawn_check_exit_status().
967 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
968 * @cancellable was cancelled
973 g_subprocess_wait_check (GSubprocess *subprocess,
974 GCancellable *cancellable,
977 return g_subprocess_wait (subprocess, cancellable, error) &&
978 g_spawn_check_exit_status (subprocess->status, error);
982 * g_subprocess_wait_check_async:
983 * @subprocess: a #GSubprocess
984 * @cancellable: a #GCancellable, or %NULL
985 * @callback: a #GAsyncReadyCallback to call when the operation is complete
986 * @user_data: user_data for @callback
988 * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
990 * This is the asynchronous version of g_subprocess_wait_check().
995 g_subprocess_wait_check_async (GSubprocess *subprocess,
996 GCancellable *cancellable,
997 GAsyncReadyCallback callback,
1000 g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
1004 * g_subprocess_wait_check_finish:
1005 * @subprocess: a #GSubprocess
1006 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
1007 * @error: a pointer to a %NULL #GError, or %NULL
1009 * Collects the result of a previous call to
1010 * g_subprocess_wait_check_async().
1012 * Returns: %TRUE if successful, or %FALSE with @error set
1017 g_subprocess_wait_check_finish (GSubprocess *subprocess,
1018 GAsyncResult *result,
1021 return g_subprocess_wait_finish (subprocess, result, error) &&
1022 g_spawn_check_exit_status (subprocess->status, error);
1028 GSubprocess *subprocess;
1033 g_subprocess_actually_send_signal (gpointer user_data)
1035 SignalRecord *signal_record = user_data;
1037 /* The pid is set to zero from the worker thread as well, so we don't
1038 * need to take a lock in order to prevent it from changing under us.
1040 if (signal_record->subprocess->pid)
1041 kill (signal_record->subprocess->pid, signal_record->signalnum);
1043 g_object_unref (signal_record->subprocess);
1045 g_slice_free (SignalRecord, signal_record);
1051 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1054 SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1056 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1058 /* This MUST be a lower priority than the priority that the child
1059 * watch source uses in initable_init().
1061 * Reaping processes, reporting the results back to GSubprocess and
1062 * sending signals is all done in the glib worker thread. We cannot
1063 * have a kill() done after the reap and before the report without
1064 * risking killing a process that's no longer there so the kill()
1065 * needs to have the lower priority.
1067 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1069 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1070 G_PRIORITY_HIGH_IDLE,
1071 g_subprocess_actually_send_signal,
1072 g_slice_dup (SignalRecord, &signal_record),
1077 * g_subprocess_send_signal:
1078 * @subprocess: a #GSubprocess
1079 * @signal_num: the signal number to send
1081 * Sends the UNIX signal @signal_num to the subprocess, if it is still
1084 * This API is race-free. If the subprocess has terminated, it will not
1087 * This API is not available on Windows.
1092 g_subprocess_send_signal (GSubprocess *subprocess,
1095 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1097 g_subprocess_dispatch_signal (subprocess, signal_num);
1102 * g_subprocess_force_exit:
1103 * @subprocess: a #GSubprocess
1105 * Use an operating-system specific method to attempt an immediate,
1106 * forceful termination of the process. There is no mechanism to
1107 * determine whether or not the request itself was successful;
1108 * however, you can use g_subprocess_wait() to monitor the status of
1109 * the process after calling this function.
1111 * On Unix, this function sends %SIGKILL.
1116 g_subprocess_force_exit (GSubprocess *subprocess)
1118 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1121 g_subprocess_dispatch_signal (subprocess, SIGKILL);
1123 TerminateProcess (subprocess->pid, 1);
1128 * g_subprocess_get_status:
1129 * @subprocess: a #GSubprocess
1131 * Gets the raw status code of the process, as from waitpid().
1133 * This value has no particular meaning, but it can be used with the
1134 * macros defined by the system headers such as WIFEXITED. It can also
1135 * be used with g_spawn_check_exit_status().
1137 * It is more likely that you want to use g_subprocess_get_if_exited()
1138 * followed by g_subprocess_get_exit_status().
1140 * It is an error to call this function before g_subprocess_wait() has
1143 * Returns: the (meaningless) waitpid() exit status from the kernel
1148 g_subprocess_get_status (GSubprocess *subprocess)
1150 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1151 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1153 return subprocess->status;
1157 * g_subprocess_get_successful:
1158 * @subprocess: a #GSubprocess
1160 * Checks if the process was "successful". A process is considered
1161 * successful if it exited cleanly with an exit status of 0, either by
1162 * way of the exit() system call or return from main().
1164 * It is an error to call this function before g_subprocess_wait() has
1167 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1172 g_subprocess_get_successful (GSubprocess *subprocess)
1174 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1175 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1178 return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1180 return subprocess->status == 0;
1185 * g_subprocess_get_if_exited:
1186 * @subprocess: a #GSubprocess
1188 * Check if the given subprocess exited normally (ie: by way of exit()
1189 * or return from main()).
1191 * This is equivalent to the system WIFEXITED macro.
1193 * It is an error to call this function before g_subprocess_wait() has
1196 * Returns: %TRUE if the case of a normal exit
1201 g_subprocess_get_if_exited (GSubprocess *subprocess)
1203 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1204 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1207 return WIFEXITED (subprocess->status);
1214 * g_subprocess_get_exit_status:
1215 * @subprocess: a #GSubprocess
1217 * Check the exit status of the subprocess, given that it exited
1218 * normally. This is the value passed to the exit() system call or the
1219 * return value from main.
1221 * This is equivalent to the system WEXITSTATUS macro.
1223 * It is an error to call this function before g_subprocess_wait() and
1224 * unless g_subprocess_get_if_exited() returned %TRUE.
1226 * Returns: the exit status
1231 g_subprocess_get_exit_status (GSubprocess *subprocess)
1233 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1234 g_return_val_if_fail (subprocess->pid == 0, 1);
1237 g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1239 return WEXITSTATUS (subprocess->status);
1241 return subprocess->status;
1246 * g_subprocess_get_if_signaled:
1247 * @subprocess: a #GSubprocess
1249 * Check if the given subprocess terminated in response to a signal.
1251 * This is equivalent to the system WIFSIGNALED macro.
1253 * It is an error to call this function before g_subprocess_wait() has
1256 * Returns: %TRUE if the case of termination due to a signal
1261 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1263 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1264 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1267 return WIFSIGNALED (subprocess->status);
1274 * g_subprocess_get_term_sig:
1275 * @subprocess: a #GSubprocess
1277 * Get the signal number that caused the subprocess to terminate, given
1278 * that it terminated due to a signal.
1280 * This is equivalent to the system WTERMSIG macro.
1282 * It is an error to call this function before g_subprocess_wait() and
1283 * unless g_subprocess_get_if_signaled() returned %TRUE.
1285 * Returns: the signal causing termination
1290 g_subprocess_get_term_sig (GSubprocess *subprocess)
1292 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1293 g_return_val_if_fail (subprocess->pid == 0, 0);
1296 g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1298 return WTERMSIG (subprocess->status);
1300 g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1301 "g_subprocess_get_if_signaled() always returns FALSE...");
1308 g_subprocess_set_launcher (GSubprocess *subprocess,
1309 GSubprocessLauncher *launcher)
1311 subprocess->launcher = launcher;
1315 /* g_subprocess_communicate implementation below:
1317 * This is a tough problem. We have to watch 5 things at the same time:
1319 * - writing to stdin made progress
1320 * - reading from stdout made progress
1321 * - reading from stderr made progress
1322 * - process terminated
1323 * - cancellable being cancelled by caller
1325 * We use a GMainContext for all of these (either as async function
1326 * calls or as a GSource (in the case of the cancellable). That way at
1327 * least we don't have to worry about threading.
1329 * For the sync case we use the usual trick of creating a private main
1330 * context and iterating it until completion.
1332 * It's very possible that the process will dump a lot of data to stdout
1333 * just before it quits, so we can easily have data to read from stdout
1334 * and see the process has terminated at the same time. We want to make
1335 * sure that we read all of the data from the pipes first, though, so we
1336 * do IO operations at a higher priority than the wait operation (which
1337 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1338 * multiple reads to get this data, the pipe() will always be polling
1339 * as ready and with the async result for the read at a higher priority,
1340 * the main context will not dispatch the completion for the wait().
1342 * We keep our own private GCancellable. In the event that any of the
1343 * above suffers from an error condition (including the user cancelling
1344 * their cancellable) we immediately dispatch the GTask with the error
1345 * result and fire our cancellable to cleanup any pending operations.
1346 * In the case that the error is that the user's cancellable was fired,
1347 * it's vaguely wasteful to report an error because GTask will handle
1348 * this automatically, so we just return FALSE.
1350 * We let each pending sub-operation take a ref on the GTask of the
1351 * communicate operation. We have to be careful that we don't report
1352 * the task completion more than once, though, so we keep a flag for
1357 const gchar *stdin_data;
1363 GInputStream *stdin_buf;
1364 GMemoryOutputStream *stdout_buf;
1365 GMemoryOutputStream *stderr_buf;
1367 GCancellable *cancellable;
1368 GSource *cancellable_source;
1370 guint outstanding_ops;
1371 gboolean reported_error;
1375 g_subprocess_communicate_made_progress (GObject *source_object,
1376 GAsyncResult *result,
1379 CommunicateState *state;
1380 GSubprocess *subprocess;
1381 GError *error = NULL;
1385 g_assert (source_object != NULL);
1388 subprocess = g_task_get_source_object (task);
1389 state = g_task_get_task_data (task);
1390 source = source_object;
1392 state->outstanding_ops--;
1394 if (source == subprocess->stdin_pipe ||
1395 source == state->stdout_buf ||
1396 source == state->stderr_buf)
1398 if (!g_output_stream_splice_finish ((GOutputStream*)source, result, &error))
1401 if (source == state->stdout_buf ||
1402 source == state->stderr_buf)
1404 /* This is a memory stream, so it can't be cancelled or return
1409 gsize bytes_written;
1410 if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1414 if (!g_output_stream_close (source, NULL, &error))
1418 else if (source == subprocess)
1420 (void) g_subprocess_wait_finish (subprocess, result, &error);
1423 g_assert_not_reached ();
1428 /* Only report the first error we see.
1430 * We might be seeing an error as a result of the cancellation
1431 * done when the process quits.
1433 if (!state->reported_error)
1435 state->reported_error = TRUE;
1436 g_cancellable_cancel (state->cancellable);
1437 g_task_return_error (task, error);
1440 g_error_free (error);
1442 else if (state->outstanding_ops == 0)
1444 g_task_return_boolean (task, TRUE);
1447 /* And drop the original ref */
1448 g_object_unref (task);
1452 g_subprocess_communicate_cancelled (gpointer user_data)
1454 CommunicateState *state = user_data;
1456 g_cancellable_cancel (state->cancellable);
1462 g_subprocess_communicate_state_free (gpointer data)
1464 CommunicateState *state = data;
1466 g_clear_object (&state->stdin_buf);
1467 g_clear_object (&state->stdout_buf);
1468 g_clear_object (&state->stderr_buf);
1470 if (!g_source_is_destroyed (state->cancellable_source))
1471 g_source_destroy (state->cancellable_source);
1472 g_source_unref (state->cancellable_source);
1474 g_slice_free (CommunicateState, state);
1477 static CommunicateState *
1478 g_subprocess_communicate_internal (GSubprocess *subprocess,
1481 GCancellable *cancellable,
1482 GAsyncReadyCallback callback,
1485 CommunicateState *state;
1488 task = g_task_new (subprocess, cancellable, callback, user_data);
1489 state = g_slice_new0 (CommunicateState);
1490 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1492 state->cancellable = g_cancellable_new ();
1493 state->add_nul = add_nul;
1497 state->cancellable_source = g_cancellable_source_new (cancellable);
1498 /* No ref held here, but we unref the source from state's free function */
1499 g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1500 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1503 if (subprocess->stdin_pipe)
1505 g_assert (stdin_buf != NULL);
1506 state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1507 g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1508 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1509 G_PRIORITY_DEFAULT, state->cancellable,
1510 g_subprocess_communicate_made_progress, g_object_ref (task));
1511 state->outstanding_ops++;
1514 if (subprocess->stdout_pipe)
1516 state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1517 g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1518 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1519 G_PRIORITY_DEFAULT, state->cancellable,
1520 g_subprocess_communicate_made_progress, g_object_ref (task));
1521 state->outstanding_ops++;
1524 if (subprocess->stderr_pipe)
1526 state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1527 g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1528 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1529 G_PRIORITY_DEFAULT, state->cancellable,
1530 g_subprocess_communicate_made_progress, g_object_ref (task));
1531 state->outstanding_ops++;
1534 g_subprocess_wait_async (subprocess, state->cancellable,
1535 g_subprocess_communicate_made_progress, g_object_ref (task));
1536 state->outstanding_ops++;
1542 * g_subprocess_communicate:
1543 * @subprocess: a #GSubprocess
1544 * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1545 * @cancellable: a #GCancellable
1546 * @stdout_buf: (out): data read from the subprocess stdout
1547 * @stderr_buf: (out): data read from the subprocess stderr
1548 * @error: a pointer to a %NULL #GError pointer, or %NULL
1550 * Communicate with the subprocess until it terminates, and all input
1551 * and output has been completed.
1553 * If @stdin is given, the subprocess must have been created with
1554 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1555 * stdin of the subprocess and the pipe is closed (ie: EOF).
1557 * At the same time (as not to cause blocking when dealing with large
1558 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1559 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1560 * streams. The data that was read is returned in @stdout and/or
1563 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1564 * @stdout_buf will contain the data read from stdout. Otherwise, for
1565 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1566 * @stdout_buf will be set to %NULL. Similar provisions apply to
1567 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1569 * As usual, any output variable may be given as %NULL to ignore it.
1571 * If you desire the stdout and stderr data to be interleaved, create
1572 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1573 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1574 * in @stdout_buf and @stderr_buf will be set to %NULL.
1576 * In case of any error (including cancellation), %FALSE will be
1577 * returned with @error set. Some or all of the stdin data may have
1578 * been written. Any stdout or stderr data that has been read will be
1579 * discarded. None of the out variables (aside from @error) will have
1580 * been set to anything in particular and should not be inspected.
1582 * In the case that %TRUE is returned, the subprocess has exited and the
1583 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1584 * g_subprocess_get_exit_status()) may be used.
1586 * You should not attempt to use any of the subprocess pipes after
1587 * starting this function, since they may be left in strange states,
1588 * even if the operation was cancelled. You should especially not
1589 * attempt to interact with the pipes while the operation is in progress
1590 * (either from another thread or if using the asynchronous version).
1592 * Returns: %TRUE if successful
1597 g_subprocess_communicate (GSubprocess *subprocess,
1599 GCancellable *cancellable,
1600 GBytes **stdout_buf,
1601 GBytes **stderr_buf,
1604 GAsyncResult *result = NULL;
1607 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1608 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1609 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1610 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1612 g_subprocess_sync_setup ();
1613 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1614 g_subprocess_sync_done, &result);
1615 g_subprocess_sync_complete (&result);
1616 success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1617 g_object_unref (result);
1623 * g_subprocess_communicate_async:
1625 * @stdin_buf: Input data
1626 * @cancellable: Cancellable
1627 * @callback: Callback
1628 * @user_data: User data
1630 * Asynchronous version of g_subprocess_communicate(). Complete
1631 * invocation with g_subprocess_communicate_finish().
1634 g_subprocess_communicate_async (GSubprocess *subprocess,
1636 GCancellable *cancellable,
1637 GAsyncReadyCallback callback,
1640 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1641 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1642 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1644 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1648 * g_subprocess_communicate_finish:
1651 * @stdout_buf: (out): Return location for stdout data
1652 * @stderr_buf: (out): Return location for stderr data
1655 * Complete an invocation of g_subprocess_communicate_async().
1658 g_subprocess_communicate_finish (GSubprocess *subprocess,
1659 GAsyncResult *result,
1660 GBytes **stdout_buf,
1661 GBytes **stderr_buf,
1665 CommunicateState *state;
1667 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1668 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1669 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1671 g_object_ref (result);
1673 state = g_task_get_task_data ((GTask*)result);
1674 success = g_task_propagate_boolean ((GTask*)result, error);
1679 *stdout_buf = g_memory_output_stream_steal_as_bytes (state->stdout_buf);
1681 *stderr_buf = g_memory_output_stream_steal_as_bytes (state->stderr_buf);
1684 g_object_unref (result);
1689 * g_subprocess_communicate_utf8:
1690 * @subprocess: a #GSubprocess
1691 * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1692 * @cancellable: a #GCancellable
1693 * @stdout_buf: (out): data read from the subprocess stdout
1694 * @stderr_buf: (out): data read from the subprocess stderr
1695 * @error: a pointer to a %NULL #GError pointer, or %NULL
1697 * Like g_subprocess_communicate(), but validates the output of the
1698 * process as UTF-8, and returns it as a regular NUL terminated string.
1701 g_subprocess_communicate_utf8 (GSubprocess *subprocess,
1702 const char *stdin_buf,
1703 GCancellable *cancellable,
1708 GAsyncResult *result = NULL;
1710 GBytes *stdin_bytes;
1712 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1713 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1714 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1715 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1717 stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1719 g_subprocess_sync_setup ();
1720 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1721 g_subprocess_sync_done, &result);
1722 g_subprocess_sync_complete (&result);
1723 success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1724 g_object_unref (result);
1726 g_bytes_unref (stdin_bytes);
1731 * g_subprocess_communicate_utf8_async:
1733 * @stdin_buf: Input data
1734 * @cancellable: Cancellable
1735 * @callback: Callback
1736 * @user_data: User data
1738 * Asynchronous version of g_subprocess_communicate_utf(). Complete
1739 * invocation with g_subprocess_communicate_utf8_finish().
1742 g_subprocess_communicate_utf8_async (GSubprocess *subprocess,
1743 const char *stdin_buf,
1744 GCancellable *cancellable,
1745 GAsyncReadyCallback callback,
1748 GBytes *stdin_bytes;
1750 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1751 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1752 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1754 stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1755 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1756 g_bytes_unref (stdin_bytes);
1760 communicate_result_validate_utf8 (const char *stream_name,
1761 char **return_location,
1762 GMemoryOutputStream *buffer,
1765 if (return_location == NULL)
1771 *return_location = g_memory_output_stream_steal_data (buffer);
1772 if (!g_utf8_validate (*return_location, -1, &end))
1774 g_free (*return_location);
1775 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1776 "Invalid UTF-8 in child %s at offset %lu",
1778 (unsigned long) (end - *return_location));
1783 *return_location = NULL;
1789 * g_subprocess_communicate_utf8_finish:
1792 * @stdout_buf: (out): Return location for stdout data
1793 * @stderr_buf: (out): Return location for stderr data
1796 * Complete an invocation of g_subprocess_communicate_utf8_async().
1799 g_subprocess_communicate_utf8_finish (GSubprocess *subprocess,
1800 GAsyncResult *result,
1805 gboolean ret = FALSE;
1806 CommunicateState *state;
1808 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1809 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1810 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1812 g_object_ref (result);
1814 state = g_task_get_task_data ((GTask*)result);
1815 if (!g_task_propagate_boolean ((GTask*)result, error))
1818 /* TODO - validate UTF-8 while streaming, rather than all at once.
1820 if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1824 if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1831 g_object_unref (result);