1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2012, 2013 Red Hat, Inc.
4 * Copyright © 2012, 2013 Canonical Limited
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * See the included COPYING file for more information.
15 * Authors: Colin Walters <walters@verbum.org>
16 * Ryan Lortie <desrt@desrt.ca>
22 * @short_description: Child processes
24 * @see_also: #GSubprocessLauncher
26 * #GSubprocess allows the creation of and interaction with child
29 * Processes can be communicated with using standard GIO-style APIs (ie:
30 * #GInputStream, #GOutputStream). There are GIO-style APIs to wait for
31 * process termination (ie: cancellable and with an asynchronous
34 * There is an API to force a process to terminate, as well as a
35 * race-free API for sending UNIX signals to a subprocess.
37 * One major advantage that GIO brings over the core GLib library is
38 * comprehensive API for asynchronous I/O, such
39 * g_output_stream_splice_async(). This makes GSubprocess
40 * significantly more powerful and flexible than equivalent APIs in
41 * some other languages such as the `subprocess.py`
42 * included with Python. For example, using #GSubprocess one could
43 * create two child processes, reading standard output from the first,
44 * processing it, and writing to the input stream of the second, all
45 * without blocking the main loop.
47 * A powerful g_subprocess_communicate() API is provided similar to the
48 * `communicate()` method of `subprocess.py`. This enables very easy
49 * interaction with a subprocess that has been opened with pipes.
51 * #GSubprocess defaults to tight control over the file descriptors open
52 * in the child process, avoiding dangling-fd issues that are caused by
53 * a simple fork()/exec(). The only open file descriptors in the
54 * spawned process are ones that were explicitly specified by the
55 * #GSubprocess API (unless %G_SUBPROCESS_FLAGS_INHERIT_FDS was
58 * #GSubprocess will quickly reap all child processes as they exit,
59 * avoiding "zombie processes" remaining around for long periods of
60 * time. g_subprocess_wait() can be used to wait for this to happen,
61 * but it will happen even without the call being explicitly made.
63 * As a matter of principle, #GSubprocess has no API that accepts
64 * shell-style space-separated strings. It will, however, match the
65 * typical shell behaviour of searching the PATH for executables that do
66 * not contain a directory separator in their name. By default, the `PATH`
67 * of the current process is used. You can specify
68 * %G_SUBPROCESS_FLAGS_SEARCH_PATH_FROM_ENVP to use the `PATH` of the
69 * launcher environment instead.
71 * #GSubprocess attempts to have a very simple API for most uses (ie:
72 * spawning a subprocess with arguments and support for most typical
73 * kinds of input and output redirection). See g_subprocess_new(). The
74 * #GSubprocessLauncher API is provided for more complicated cases
75 * (advanced types of redirection, environment variable manipulation,
76 * change of working directory, child setup functions, etc).
78 * A typical use of #GSubprocess will involve calling
79 * g_subprocess_new(), followed by g_subprocess_wait_async() or
80 * g_subprocess_wait(). After the process exits, the status can be
81 * checked using functions such as g_subprocess_get_if_exited() (which
82 * are similar to the familiar WIFEXITED-style POSIX macros).
89 #include "gsubprocess.h"
90 #include "gsubprocesslauncher-private.h"
91 #include "gasyncresult.h"
92 #include "giostream.h"
93 #include "gmemoryinputstream.h"
95 #include "glib-private.h"
99 #include <gio/gunixoutputstream.h>
100 #include <gio/gfiledescriptorbased.h>
101 #include <gio/gunixinputstream.h>
103 #include <glib-unix.h>
109 #include "giowin32-priv.h"
119 #define HAVE_O_CLOEXEC 1
122 #define COMMUNICATE_READ_SIZE 4096
124 /* A GSubprocess can have two possible states: running and not.
126 * These two states are reflected by the value of 'pid'. If it is
127 * non-zero then the process is running, with that pid.
129 * When a GSubprocess is first created with g_object_new() it is not
130 * running. When it is finalized, it is also not running.
132 * During initable_init(), if the g_spawn() is successful then we
133 * immediately register a child watch and take an extra ref on the
134 * subprocess. That reference doesn't drop until the child has quit,
135 * which is why finalize can only happen in the non-running state. In
136 * the event that the g_spawn() failed we will still be finalizing a
137 * non-running GSubprocess (before returning from g_subprocess_new())
140 * We make extensive use of the glib worker thread to guarantee
141 * race-free operation. As with all child watches, glib calls waitpid()
142 * in the worker thread. It reports the child exiting to us via the
143 * worker thread (which means that we can do synchronous waits without
144 * running a separate loop). We also send signals to the child process
145 * via the worker thread so that we don't race with waitpid() and
146 * accidentally send a signal to an already-reaped child.
148 static void initable_iface_init (GInitableIface *initable_iface);
150 typedef GObjectClass GSubprocessClass;
156 /* only used during construction */
157 GSubprocessLauncher *launcher;
158 GSubprocessFlags flags;
161 /* state tracking variables */
162 gchar identifier[24];
167 GMutex pending_waits_lock;
168 GSList *pending_waits;
170 /* These are the streams created if a pipe is requested via flags. */
171 GOutputStream *stdin_pipe;
172 GInputStream *stdout_pipe;
173 GInputStream *stderr_pipe;
176 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
177 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))
187 static GInputStream *
188 platform_input_stream_from_spawn_fd (gint fd)
194 return g_unix_input_stream_new (fd, TRUE);
196 return g_win32_input_stream_new_from_fd (fd, TRUE);
200 static GOutputStream *
201 platform_output_stream_from_spawn_fd (gint fd)
207 return g_unix_output_stream_new (fd, TRUE);
209 return g_win32_output_stream_new_from_fd (fd, TRUE);
215 unix_open_file (const char *filename,
221 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
223 /* If we return -1 we should also set the error */
226 gint saved_errno = errno;
229 display_name = g_filename_display_name (filename);
230 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
231 _("Error opening file “%s”: %s"), display_name,
232 g_strerror (saved_errno));
233 g_free (display_name);
234 /* fall through... */
236 #ifndef HAVE_O_CLOEXEC
238 fcntl (my_fd, F_SETFD, FD_CLOEXEC);
246 g_subprocess_set_property (GObject *object,
251 GSubprocess *self = G_SUBPROCESS (object);
256 self->flags = g_value_get_flags (value);
260 self->argv = g_value_dup_boxed (value);
264 g_assert_not_reached ();
269 g_subprocess_exited (GPid pid,
273 GSubprocess *self = user_data;
276 g_assert (self->pid == pid);
278 g_mutex_lock (&self->pending_waits_lock);
279 self->status = status;
280 tasks = self->pending_waits;
281 self->pending_waits = NULL;
283 g_mutex_unlock (&self->pending_waits_lock);
285 /* Signal anyone in g_subprocess_wait_async() to wake up now */
288 g_task_return_boolean (tasks->data, TRUE);
289 g_object_unref (tasks->data);
290 tasks = g_slist_delete_link (tasks, tasks);
293 g_spawn_close_pid (pid);
299 initable_init (GInitable *initable,
300 GCancellable *cancellable,
303 GSubprocess *self = G_SUBPROCESS (initable);
304 gint *pipe_ptrs[3] = { NULL, NULL, NULL };
305 gint pipe_fds[3] = { -1, -1, -1 };
306 gint close_fds[3] = { -1, -1, -1 };
308 gint stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
310 GSpawnFlags spawn_flags = 0;
311 gboolean success = FALSE;
314 /* this is a programmer error */
315 if (!self->argv || !self->argv[0] || !self->argv[0][0])
318 if (g_cancellable_set_error_if_cancelled (cancellable, error))
321 /* We must setup the three fds that will end up in the child as stdin,
326 if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
327 spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
328 else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
329 pipe_ptrs[0] = &pipe_fds[0];
331 else if (self->launcher)
333 if (self->launcher->stdin_fd != -1)
334 stdin_fd = self->launcher->stdin_fd;
335 else if (self->launcher->stdin_path != NULL)
337 stdin_fd = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
345 if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
346 spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
347 else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
348 pipe_ptrs[1] = &pipe_fds[1];
350 else if (self->launcher)
352 if (self->launcher->stdout_fd != -1)
353 stdout_fd = self->launcher->stdout_fd;
354 else if (self->launcher->stdout_path != NULL)
356 stdout_fd = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
363 /* Finally, stderr. */
364 if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
365 spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
366 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
367 pipe_ptrs[2] = &pipe_fds[2];
369 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
370 /* This will work because stderr gets set up after stdout. */
372 else if (self->launcher)
374 if (self->launcher->stderr_fd != -1)
375 stderr_fd = self->launcher->stderr_fd;
376 else if (self->launcher->stderr_path != NULL)
378 stderr_fd = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
385 /* argv0 has no '/' in it? We better do a PATH lookup. */
386 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
388 if (self->launcher && self->launcher->flags & G_SUBPROCESS_FLAGS_SEARCH_PATH_FROM_ENVP)
389 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
391 spawn_flags |= G_SPAWN_SEARCH_PATH;
394 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
395 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
397 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
398 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
400 success = g_spawn_async_with_pipes_and_fds (self->launcher ? self->launcher->cwd : NULL,
401 (const gchar * const *) self->argv,
402 (const gchar * const *) (self->launcher ? self->launcher->envp : NULL),
405 self->launcher ? self->launcher->child_setup_func : NULL,
406 self->launcher ? self->launcher->child_setup_user_data : NULL,
407 stdin_fd, stdout_fd, stderr_fd,
408 self->launcher ? (const gint *) self->launcher->source_fds->data : NULL,
409 self->launcher ? (const gint *) self->launcher->target_fds->data : NULL,
410 self->launcher ? self->launcher->source_fds->len : 0,
417 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
419 g_assert (success == (self->pid != 0));
423 gint s G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
426 identifier = (guint64) GetProcessId (self->pid);
428 identifier = (guint64) self->pid;
431 s = g_snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
432 g_assert (0 < s && (gsize) s < sizeof self->identifier);
435 /* Start attempting to reap the child immediately */
438 GMainContext *worker_context;
441 worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
442 source = g_child_watch_source_new (self->pid);
443 g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
444 g_source_attach (source, worker_context);
445 g_source_unref (source);
451 /* we don't need this past init... */
452 self->launcher = NULL;
454 for (i = 0; i < 3; i++)
455 if (close_fds[i] != -1)
456 close (close_fds[i]);
458 self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
459 self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
460 self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
466 g_subprocess_finalize (GObject *object)
468 GSubprocess *self = G_SUBPROCESS (object);
470 g_assert (self->pending_waits == NULL);
471 g_assert (self->pid == 0);
473 g_clear_object (&self->stdin_pipe);
474 g_clear_object (&self->stdout_pipe);
475 g_clear_object (&self->stderr_pipe);
476 g_strfreev (self->argv);
478 g_mutex_clear (&self->pending_waits_lock);
480 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
484 g_subprocess_init (GSubprocess *self)
486 g_mutex_init (&self->pending_waits_lock);
490 initable_iface_init (GInitableIface *initable_iface)
492 initable_iface->init = initable_init;
496 g_subprocess_class_init (GSubprocessClass *class)
498 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
500 gobject_class->finalize = g_subprocess_finalize;
501 gobject_class->set_property = g_subprocess_set_property;
503 g_object_class_install_property (gobject_class, PROP_FLAGS,
504 g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
505 G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
506 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
507 g_object_class_install_property (gobject_class, PROP_ARGV,
508 g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
509 G_TYPE_STRV, G_PARAM_WRITABLE |
510 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
514 * g_subprocess_new: (skip)
515 * @flags: flags that define the behaviour of the subprocess
516 * @error: (nullable): return location for an error, or %NULL
517 * @argv0: first commandline argument to pass to the subprocess
518 * @...: more commandline arguments, followed by %NULL
520 * Create a new process with the given flags and varargs argument
521 * list. By default, matching the g_spawn_async() defaults, the
522 * child's stdin will be set to the system null device, and
523 * stdout/stderr will be inherited from the parent. You can use
524 * @flags to control this behavior.
526 * The argument list must be terminated with %NULL.
528 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
534 g_subprocess_new (GSubprocessFlags flags,
544 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
545 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
547 args = g_ptr_array_new ();
549 va_start (ap, argv0);
550 g_ptr_array_add (args, (gchar *) argv0);
551 while ((arg = va_arg (ap, const gchar *)))
552 g_ptr_array_add (args, (gchar *) arg);
553 g_ptr_array_add (args, NULL);
556 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
558 g_ptr_array_free (args, TRUE);
564 * g_subprocess_newv: (rename-to g_subprocess_new)
565 * @argv: (array zero-terminated=1) (element-type filename): commandline arguments for the subprocess
566 * @flags: flags that define the behaviour of the subprocess
567 * @error: (nullable): return location for an error, or %NULL
569 * Create a new process with the given flags and argument list.
571 * The argument list is expected to be %NULL-terminated.
573 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
579 g_subprocess_newv (const gchar * const *argv,
580 GSubprocessFlags flags,
583 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
585 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
592 * g_subprocess_get_identifier:
593 * @subprocess: a #GSubprocess
595 * On UNIX, returns the process ID as a decimal string.
596 * On Windows, returns the result of GetProcessId() also as a string.
597 * If the subprocess has terminated, this will return %NULL.
599 * Returns: (nullable): the subprocess identifier, or %NULL if the subprocess
604 g_subprocess_get_identifier (GSubprocess *subprocess)
606 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
609 return subprocess->identifier;
615 * g_subprocess_get_stdin_pipe:
616 * @subprocess: a #GSubprocess
618 * Gets the #GOutputStream that you can write to in order to give data
619 * to the stdin of @subprocess.
621 * The process must have been created with %G_SUBPROCESS_FLAGS_STDIN_PIPE and
622 * not %G_SUBPROCESS_FLAGS_STDIN_INHERIT, otherwise %NULL will be returned.
624 * Returns: (nullable) (transfer none): the stdout pipe
629 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
631 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
633 return subprocess->stdin_pipe;
637 * g_subprocess_get_stdout_pipe:
638 * @subprocess: a #GSubprocess
640 * Gets the #GInputStream from which to read the stdout output of
643 * The process must have been created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
644 * otherwise %NULL will be returned.
646 * Returns: (nullable) (transfer none): the stdout pipe
651 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
653 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
655 return subprocess->stdout_pipe;
659 * g_subprocess_get_stderr_pipe:
660 * @subprocess: a #GSubprocess
662 * Gets the #GInputStream from which to read the stderr output of
665 * The process must have been created with %G_SUBPROCESS_FLAGS_STDERR_PIPE,
666 * otherwise %NULL will be returned.
668 * Returns: (nullable) (transfer none): the stderr pipe
673 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
675 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
677 return subprocess->stderr_pipe;
680 /* Remove the first list element containing @data, and return %TRUE. If no
681 * such element is found, return %FALSE. */
683 slist_remove_if_present (GSList **list,
688 for (l = *list, prev = NULL; l != NULL; prev = l, l = prev->next)
693 prev->next = l->next;
707 g_subprocess_wait_cancelled (GCancellable *cancellable,
710 GTask *task = user_data;
712 gboolean task_was_pending;
714 self = g_task_get_source_object (task);
716 g_mutex_lock (&self->pending_waits_lock);
717 task_was_pending = slist_remove_if_present (&self->pending_waits, task);
718 g_mutex_unlock (&self->pending_waits_lock);
720 if (task_was_pending)
722 g_task_return_boolean (task, FALSE);
723 g_object_unref (task); /* ref from pending_waits */
728 * g_subprocess_wait_async:
729 * @subprocess: a #GSubprocess
730 * @cancellable: a #GCancellable, or %NULL
731 * @callback: a #GAsyncReadyCallback to call when the operation is complete
732 * @user_data: user_data for @callback
734 * Wait for the subprocess to terminate.
736 * This is the asynchronous version of g_subprocess_wait().
741 g_subprocess_wait_async (GSubprocess *subprocess,
742 GCancellable *cancellable,
743 GAsyncReadyCallback callback,
748 task = g_task_new (subprocess, cancellable, callback, user_data);
749 g_task_set_source_tag (task, g_subprocess_wait_async);
751 g_mutex_lock (&subprocess->pending_waits_lock);
754 /* Only bother with cancellable if we're putting it in the list.
755 * If not, it's going to dispatch immediately anyway and we will
756 * see the cancellation in the _finish().
759 g_signal_connect_object (cancellable, "cancelled",
760 G_CALLBACK (g_subprocess_wait_cancelled),
761 task, G_CONNECT_DEFAULT);
763 subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
766 g_mutex_unlock (&subprocess->pending_waits_lock);
768 /* If we still have task then it's because did_exit is already TRUE */
771 g_task_return_boolean (task, TRUE);
772 g_object_unref (task);
777 * g_subprocess_wait_finish:
778 * @subprocess: a #GSubprocess
779 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
780 * @error: a pointer to a %NULL #GError, or %NULL
782 * Collects the result of a previous call to
783 * g_subprocess_wait_async().
785 * Returns: %TRUE if successful, or %FALSE with @error set
790 g_subprocess_wait_finish (GSubprocess *subprocess,
791 GAsyncResult *result,
794 return g_task_propagate_boolean (G_TASK (result), error);
797 /* Some generic helpers for emulating synchronous operations using async
801 g_subprocess_sync_setup (void)
803 g_main_context_push_thread_default (g_main_context_new ());
807 g_subprocess_sync_done (GObject *source_object,
808 GAsyncResult *result,
811 GAsyncResult **result_ptr = user_data;
813 *result_ptr = g_object_ref (result);
817 g_subprocess_sync_complete (GAsyncResult **result)
819 GMainContext *context = g_main_context_get_thread_default ();
822 g_main_context_iteration (context, TRUE);
824 g_main_context_pop_thread_default (context);
825 g_main_context_unref (context);
830 * @subprocess: a #GSubprocess
831 * @cancellable: a #GCancellable
834 * Synchronously wait for the subprocess to terminate.
836 * After the process terminates you can query its exit status with
837 * functions such as g_subprocess_get_if_exited() and
838 * g_subprocess_get_exit_status().
840 * This function does not fail in the case of the subprocess having
841 * abnormal termination. See g_subprocess_wait_check() for that.
843 * Cancelling @cancellable doesn't kill the subprocess. Call
844 * g_subprocess_force_exit() if it is desirable.
846 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
851 g_subprocess_wait (GSubprocess *subprocess,
852 GCancellable *cancellable,
855 GAsyncResult *result = NULL;
858 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
860 /* Synchronous waits are actually the 'more difficult' case because we
861 * need to deal with the possibility of cancellation. That more or
862 * less implies that we need a main context (to dispatch either of the
863 * possible reasons for the operation ending).
865 * So we make one and then do this async...
868 if (g_cancellable_set_error_if_cancelled (cancellable, error))
871 /* We can shortcut in the case that the process already quit (but only
872 * after we checked the cancellable).
874 if (subprocess->pid == 0)
877 /* Otherwise, we need to do this the long way... */
878 g_subprocess_sync_setup ();
879 g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
880 g_subprocess_sync_complete (&result);
881 success = g_subprocess_wait_finish (subprocess, result, error);
882 g_object_unref (result);
888 * g_subprocess_wait_check:
889 * @subprocess: a #GSubprocess
890 * @cancellable: a #GCancellable
893 * Combines g_subprocess_wait() with g_spawn_check_wait_status().
895 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
896 * @cancellable was cancelled
901 g_subprocess_wait_check (GSubprocess *subprocess,
902 GCancellable *cancellable,
905 return g_subprocess_wait (subprocess, cancellable, error) &&
906 g_spawn_check_wait_status (subprocess->status, error);
910 * g_subprocess_wait_check_async:
911 * @subprocess: a #GSubprocess
912 * @cancellable: a #GCancellable, or %NULL
913 * @callback: a #GAsyncReadyCallback to call when the operation is complete
914 * @user_data: user_data for @callback
916 * Combines g_subprocess_wait_async() with g_spawn_check_wait_status().
918 * This is the asynchronous version of g_subprocess_wait_check().
923 g_subprocess_wait_check_async (GSubprocess *subprocess,
924 GCancellable *cancellable,
925 GAsyncReadyCallback callback,
928 g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
932 * g_subprocess_wait_check_finish:
933 * @subprocess: a #GSubprocess
934 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
935 * @error: a pointer to a %NULL #GError, or %NULL
937 * Collects the result of a previous call to
938 * g_subprocess_wait_check_async().
940 * Returns: %TRUE if successful, or %FALSE with @error set
945 g_subprocess_wait_check_finish (GSubprocess *subprocess,
946 GAsyncResult *result,
949 return g_subprocess_wait_finish (subprocess, result, error) &&
950 g_spawn_check_wait_status (subprocess->status, error);
956 GSubprocess *subprocess;
961 g_subprocess_actually_send_signal (gpointer user_data)
963 SignalRecord *signal_record = user_data;
965 /* The pid is set to zero from the worker thread as well, so we don't
966 * need to take a lock in order to prevent it from changing under us.
968 if (signal_record->subprocess->pid)
969 kill (signal_record->subprocess->pid, signal_record->signalnum);
971 g_object_unref (signal_record->subprocess);
973 g_slice_free (SignalRecord, signal_record);
979 g_subprocess_dispatch_signal (GSubprocess *subprocess,
982 SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
984 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
986 /* This MUST be a lower priority than the priority that the child
987 * watch source uses in initable_init().
989 * Reaping processes, reporting the results back to GSubprocess and
990 * sending signals is all done in the glib worker thread. We cannot
991 * have a kill() done after the reap and before the report without
992 * risking killing a process that's no longer there so the kill()
993 * needs to have the lower priority.
995 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
997 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
998 G_PRIORITY_HIGH_IDLE,
999 g_subprocess_actually_send_signal,
1000 g_slice_dup (SignalRecord, &signal_record),
1005 * g_subprocess_send_signal:
1006 * @subprocess: a #GSubprocess
1007 * @signal_num: the signal number to send
1009 * Sends the UNIX signal @signal_num to the subprocess, if it is still
1012 * This API is race-free. If the subprocess has terminated, it will not
1015 * This API is not available on Windows.
1020 g_subprocess_send_signal (GSubprocess *subprocess,
1023 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1025 g_subprocess_dispatch_signal (subprocess, signal_num);
1030 * g_subprocess_force_exit:
1031 * @subprocess: a #GSubprocess
1033 * Use an operating-system specific method to attempt an immediate,
1034 * forceful termination of the process. There is no mechanism to
1035 * determine whether or not the request itself was successful;
1036 * however, you can use g_subprocess_wait() to monitor the status of
1037 * the process after calling this function.
1039 * On Unix, this function sends %SIGKILL.
1044 g_subprocess_force_exit (GSubprocess *subprocess)
1046 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1049 g_subprocess_dispatch_signal (subprocess, SIGKILL);
1051 TerminateProcess (subprocess->pid, 1);
1056 * g_subprocess_get_status:
1057 * @subprocess: a #GSubprocess
1059 * Gets the raw status code of the process, as from waitpid().
1061 * This value has no particular meaning, but it can be used with the
1062 * macros defined by the system headers such as WIFEXITED. It can also
1063 * be used with g_spawn_check_wait_status().
1065 * It is more likely that you want to use g_subprocess_get_if_exited()
1066 * followed by g_subprocess_get_exit_status().
1068 * It is an error to call this function before g_subprocess_wait() has
1071 * Returns: the (meaningless) waitpid() exit status from the kernel
1076 g_subprocess_get_status (GSubprocess *subprocess)
1078 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1079 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1081 return subprocess->status;
1085 * g_subprocess_get_successful:
1086 * @subprocess: a #GSubprocess
1088 * Checks if the process was "successful". A process is considered
1089 * successful if it exited cleanly with an exit status of 0, either by
1090 * way of the exit() system call or return from main().
1092 * It is an error to call this function before g_subprocess_wait() has
1095 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1100 g_subprocess_get_successful (GSubprocess *subprocess)
1102 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1103 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1106 return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1108 return subprocess->status == 0;
1113 * g_subprocess_get_if_exited:
1114 * @subprocess: a #GSubprocess
1116 * Check if the given subprocess exited normally (ie: by way of exit()
1117 * or return from main()).
1119 * This is equivalent to the system WIFEXITED macro.
1121 * It is an error to call this function before g_subprocess_wait() has
1124 * Returns: %TRUE if the case of a normal exit
1129 g_subprocess_get_if_exited (GSubprocess *subprocess)
1131 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1132 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1135 return WIFEXITED (subprocess->status);
1142 * g_subprocess_get_exit_status:
1143 * @subprocess: a #GSubprocess
1145 * Check the exit status of the subprocess, given that it exited
1146 * normally. This is the value passed to the exit() system call or the
1147 * return value from main.
1149 * This is equivalent to the system WEXITSTATUS macro.
1151 * It is an error to call this function before g_subprocess_wait() and
1152 * unless g_subprocess_get_if_exited() returned %TRUE.
1154 * Returns: the exit status
1159 g_subprocess_get_exit_status (GSubprocess *subprocess)
1161 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1162 g_return_val_if_fail (subprocess->pid == 0, 1);
1165 g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1167 return WEXITSTATUS (subprocess->status);
1169 return subprocess->status;
1174 * g_subprocess_get_if_signaled:
1175 * @subprocess: a #GSubprocess
1177 * Check if the given subprocess terminated in response to a signal.
1179 * This is equivalent to the system WIFSIGNALED macro.
1181 * It is an error to call this function before g_subprocess_wait() has
1184 * Returns: %TRUE if the case of termination due to a signal
1189 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1191 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1192 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1195 return WIFSIGNALED (subprocess->status);
1202 * g_subprocess_get_term_sig:
1203 * @subprocess: a #GSubprocess
1205 * Get the signal number that caused the subprocess to terminate, given
1206 * that it terminated due to a signal.
1208 * This is equivalent to the system WTERMSIG macro.
1210 * It is an error to call this function before g_subprocess_wait() and
1211 * unless g_subprocess_get_if_signaled() returned %TRUE.
1213 * Returns: the signal causing termination
1218 g_subprocess_get_term_sig (GSubprocess *subprocess)
1220 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1221 g_return_val_if_fail (subprocess->pid == 0, 0);
1224 g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1226 return WTERMSIG (subprocess->status);
1228 g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1229 "g_subprocess_get_if_signaled() always returns FALSE...");
1236 g_subprocess_set_launcher (GSubprocess *subprocess,
1237 GSubprocessLauncher *launcher)
1239 subprocess->launcher = launcher;
1243 /* g_subprocess_communicate implementation below:
1245 * This is a tough problem. We have to watch 5 things at the same time:
1247 * - writing to stdin made progress
1248 * - reading from stdout made progress
1249 * - reading from stderr made progress
1250 * - process terminated
1251 * - cancellable being cancelled by caller
1253 * We use a GMainContext for all of these (either as async function
1254 * calls or as a GSource (in the case of the cancellable). That way at
1255 * least we don't have to worry about threading.
1257 * For the sync case we use the usual trick of creating a private main
1258 * context and iterating it until completion.
1260 * It's very possible that the process will dump a lot of data to stdout
1261 * just before it quits, so we can easily have data to read from stdout
1262 * and see the process has terminated at the same time. We want to make
1263 * sure that we read all of the data from the pipes first, though, so we
1264 * do IO operations at a higher priority than the wait operation (which
1265 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1266 * multiple reads to get this data, the pipe() will always be polling
1267 * as ready and with the async result for the read at a higher priority,
1268 * the main context will not dispatch the completion for the wait().
1270 * We keep our own private GCancellable. In the event that any of the
1271 * above suffers from an error condition (including the user cancelling
1272 * their cancellable) we immediately dispatch the GTask with the error
1273 * result and fire our cancellable to cleanup any pending operations.
1274 * In the case that the error is that the user's cancellable was fired,
1275 * it's vaguely wasteful to report an error because GTask will handle
1276 * this automatically, so we just return FALSE.
1278 * We let each pending sub-operation take a ref on the GTask of the
1279 * communicate operation. We have to be careful that we don't report
1280 * the task completion more than once, though, so we keep a flag for
1285 const gchar *stdin_data;
1291 GInputStream *stdin_buf;
1292 GMemoryOutputStream *stdout_buf;
1293 GMemoryOutputStream *stderr_buf;
1295 GCancellable *cancellable;
1296 GSource *cancellable_source;
1298 guint outstanding_ops;
1299 gboolean reported_error;
1303 g_subprocess_communicate_made_progress (GObject *source_object,
1304 GAsyncResult *result,
1307 CommunicateState *state;
1308 GSubprocess *subprocess;
1309 GError *error = NULL;
1313 g_assert (source_object != NULL);
1316 subprocess = g_task_get_source_object (task);
1317 state = g_task_get_task_data (task);
1318 source = source_object;
1320 state->outstanding_ops--;
1322 if (source == subprocess->stdin_pipe ||
1323 source == state->stdout_buf ||
1324 source == state->stderr_buf)
1326 if (g_output_stream_splice_finish ((GOutputStream*) source, result, &error) == -1)
1329 if (source == state->stdout_buf ||
1330 source == state->stderr_buf)
1332 /* This is a memory stream, so it can't be cancelled or return
1337 gsize bytes_written;
1338 if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1342 if (!g_output_stream_close (source, NULL, &error))
1346 else if (source == subprocess)
1348 (void) g_subprocess_wait_finish (subprocess, result, &error);
1351 g_assert_not_reached ();
1356 /* Only report the first error we see.
1358 * We might be seeing an error as a result of the cancellation
1359 * done when the process quits.
1361 if (!state->reported_error)
1363 state->reported_error = TRUE;
1364 g_cancellable_cancel (state->cancellable);
1365 g_task_return_error (task, error);
1368 g_error_free (error);
1370 else if (state->outstanding_ops == 0)
1372 g_task_return_boolean (task, TRUE);
1375 /* And drop the original ref */
1376 g_object_unref (task);
1380 g_subprocess_communicate_cancelled (GCancellable *cancellable,
1383 CommunicateState *state = user_data;
1385 g_cancellable_cancel (state->cancellable);
1391 g_subprocess_communicate_state_free (gpointer data)
1393 CommunicateState *state = data;
1395 g_clear_object (&state->cancellable);
1396 g_clear_object (&state->stdin_buf);
1397 g_clear_object (&state->stdout_buf);
1398 g_clear_object (&state->stderr_buf);
1400 if (state->cancellable_source)
1402 g_source_destroy (state->cancellable_source);
1403 g_source_unref (state->cancellable_source);
1406 g_slice_free (CommunicateState, state);
1409 static CommunicateState *
1410 g_subprocess_communicate_internal (GSubprocess *subprocess,
1413 GCancellable *cancellable,
1414 GAsyncReadyCallback callback,
1417 CommunicateState *state;
1420 task = g_task_new (subprocess, cancellable, callback, user_data);
1421 g_task_set_source_tag (task, g_subprocess_communicate_internal);
1423 state = g_slice_new0 (CommunicateState);
1424 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1426 state->cancellable = g_cancellable_new ();
1427 state->add_nul = add_nul;
1431 state->cancellable_source = g_cancellable_source_new (cancellable);
1432 /* No ref held here, but we unref the source from state's free function */
1433 g_source_set_callback (state->cancellable_source,
1434 G_SOURCE_FUNC (g_subprocess_communicate_cancelled),
1436 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1439 if (subprocess->stdin_pipe)
1441 g_assert (stdin_buf != NULL);
1444 /* We're doing async writes to the pipe, and the async write mechanism assumes
1445 * that streams polling as writable do SOME progress (possibly partial) and then
1446 * stop, but never block.
1448 * However, for blocking pipes, unix will return writable if there is *any* space left
1449 * but still block until the full buffer size is available before returning from write.
1450 * So, to avoid async blocking on the main loop we make this non-blocking here.
1452 * It should be safe to change the fd because we're the only user at this point as
1453 * per the g_subprocess_communicate() docs, and all the code called by this function
1454 * properly handles non-blocking fds.
1456 g_unix_set_fd_nonblocking (g_unix_output_stream_get_fd (G_UNIX_OUTPUT_STREAM (subprocess->stdin_pipe)), TRUE, NULL);
1459 state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1460 g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1461 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1462 G_PRIORITY_DEFAULT, state->cancellable,
1463 g_subprocess_communicate_made_progress, g_object_ref (task));
1464 state->outstanding_ops++;
1467 if (subprocess->stdout_pipe)
1469 state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1470 g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1471 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1472 G_PRIORITY_DEFAULT, state->cancellable,
1473 g_subprocess_communicate_made_progress, g_object_ref (task));
1474 state->outstanding_ops++;
1477 if (subprocess->stderr_pipe)
1479 state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1480 g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1481 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1482 G_PRIORITY_DEFAULT, state->cancellable,
1483 g_subprocess_communicate_made_progress, g_object_ref (task));
1484 state->outstanding_ops++;
1487 g_subprocess_wait_async (subprocess, state->cancellable,
1488 g_subprocess_communicate_made_progress, g_object_ref (task));
1489 state->outstanding_ops++;
1491 g_object_unref (task);
1496 * g_subprocess_communicate:
1497 * @subprocess: a #GSubprocess
1498 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1499 * @cancellable: a #GCancellable
1500 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
1501 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
1502 * @error: a pointer to a %NULL #GError pointer, or %NULL
1504 * Communicate with the subprocess until it terminates, and all input
1505 * and output has been completed.
1507 * If @stdin_buf is given, the subprocess must have been created with
1508 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1509 * stdin of the subprocess and the pipe is closed (ie: EOF).
1511 * At the same time (as not to cause blocking when dealing with large
1512 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1513 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1514 * streams. The data that was read is returned in @stdout and/or
1517 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1518 * @stdout_buf will contain the data read from stdout. Otherwise, for
1519 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1520 * @stdout_buf will be set to %NULL. Similar provisions apply to
1521 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1523 * As usual, any output variable may be given as %NULL to ignore it.
1525 * If you desire the stdout and stderr data to be interleaved, create
1526 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1527 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1528 * in @stdout_buf and @stderr_buf will be set to %NULL.
1530 * In case of any error (including cancellation), %FALSE will be
1531 * returned with @error set. Some or all of the stdin data may have
1532 * been written. Any stdout or stderr data that has been read will be
1533 * discarded. None of the out variables (aside from @error) will have
1534 * been set to anything in particular and should not be inspected.
1536 * In the case that %TRUE is returned, the subprocess has exited and the
1537 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1538 * g_subprocess_get_exit_status()) may be used.
1540 * You should not attempt to use any of the subprocess pipes after
1541 * starting this function, since they may be left in strange states,
1542 * even if the operation was cancelled. You should especially not
1543 * attempt to interact with the pipes while the operation is in progress
1544 * (either from another thread or if using the asynchronous version).
1546 * Returns: %TRUE if successful
1551 g_subprocess_communicate (GSubprocess *subprocess,
1553 GCancellable *cancellable,
1554 GBytes **stdout_buf,
1555 GBytes **stderr_buf,
1558 GAsyncResult *result = NULL;
1561 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1562 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1563 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1564 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1566 g_subprocess_sync_setup ();
1567 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1568 g_subprocess_sync_done, &result);
1569 g_subprocess_sync_complete (&result);
1570 success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1571 g_object_unref (result);
1577 * g_subprocess_communicate_async:
1579 * @stdin_buf: (nullable): Input data, or %NULL
1580 * @cancellable: (nullable): Cancellable
1581 * @callback: Callback
1582 * @user_data: User data
1584 * Asynchronous version of g_subprocess_communicate(). Complete
1585 * invocation with g_subprocess_communicate_finish().
1588 g_subprocess_communicate_async (GSubprocess *subprocess,
1590 GCancellable *cancellable,
1591 GAsyncReadyCallback callback,
1594 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1595 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1596 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1598 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1602 * g_subprocess_communicate_finish:
1605 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
1606 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
1609 * Complete an invocation of g_subprocess_communicate_async().
1612 g_subprocess_communicate_finish (GSubprocess *subprocess,
1613 GAsyncResult *result,
1614 GBytes **stdout_buf,
1615 GBytes **stderr_buf,
1619 CommunicateState *state;
1621 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1622 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1623 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1625 g_object_ref (result);
1627 state = g_task_get_task_data ((GTask*)result);
1628 success = g_task_propagate_boolean ((GTask*)result, error);
1633 *stdout_buf = (state->stdout_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stdout_buf) : NULL;
1635 *stderr_buf = (state->stderr_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stderr_buf) : NULL;
1638 g_object_unref (result);
1643 * g_subprocess_communicate_utf8:
1644 * @subprocess: a #GSubprocess
1645 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1646 * @cancellable: a #GCancellable
1647 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
1648 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
1649 * @error: a pointer to a %NULL #GError pointer, or %NULL
1651 * Like g_subprocess_communicate(), but validates the output of the
1652 * process as UTF-8, and returns it as a regular NUL terminated string.
1654 * On error, @stdout_buf and @stderr_buf will be set to undefined values and
1655 * should not be used.
1658 g_subprocess_communicate_utf8 (GSubprocess *subprocess,
1659 const char *stdin_buf,
1660 GCancellable *cancellable,
1665 GAsyncResult *result = NULL;
1667 GBytes *stdin_bytes;
1668 size_t stdin_buf_len = 0;
1670 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1671 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1672 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1673 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1675 if (stdin_buf != NULL)
1676 stdin_buf_len = strlen (stdin_buf);
1677 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1679 g_subprocess_sync_setup ();
1680 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1681 g_subprocess_sync_done, &result);
1682 g_subprocess_sync_complete (&result);
1683 success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1684 g_object_unref (result);
1686 g_bytes_unref (stdin_bytes);
1691 * g_subprocess_communicate_utf8_async:
1693 * @stdin_buf: (nullable): Input data, or %NULL
1694 * @cancellable: Cancellable
1695 * @callback: Callback
1696 * @user_data: User data
1698 * Asynchronous version of g_subprocess_communicate_utf8(). Complete
1699 * invocation with g_subprocess_communicate_utf8_finish().
1702 g_subprocess_communicate_utf8_async (GSubprocess *subprocess,
1703 const char *stdin_buf,
1704 GCancellable *cancellable,
1705 GAsyncReadyCallback callback,
1708 GBytes *stdin_bytes;
1709 size_t stdin_buf_len = 0;
1711 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1712 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1713 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1715 if (stdin_buf != NULL)
1716 stdin_buf_len = strlen (stdin_buf);
1717 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1719 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1721 g_bytes_unref (stdin_bytes);
1725 communicate_result_validate_utf8 (const char *stream_name,
1726 char **return_location,
1727 GMemoryOutputStream *buffer,
1730 if (return_location == NULL)
1736 *return_location = g_memory_output_stream_steal_data (buffer);
1737 if (!g_utf8_validate (*return_location, -1, &end))
1739 g_free (*return_location);
1740 *return_location = NULL;
1741 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1742 "Invalid UTF-8 in child %s at offset %lu",
1744 (unsigned long) (end - *return_location));
1749 *return_location = NULL;
1755 * g_subprocess_communicate_utf8_finish:
1758 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
1759 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
1762 * Complete an invocation of g_subprocess_communicate_utf8_async().
1765 g_subprocess_communicate_utf8_finish (GSubprocess *subprocess,
1766 GAsyncResult *result,
1771 gboolean ret = FALSE;
1772 CommunicateState *state;
1773 gchar *local_stdout_buf = NULL, *local_stderr_buf = NULL;
1775 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1776 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1777 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1779 g_object_ref (result);
1781 state = g_task_get_task_data ((GTask*)result);
1782 if (!g_task_propagate_boolean ((GTask*)result, error))
1785 /* TODO - validate UTF-8 while streaming, rather than all at once.
1787 if (!communicate_result_validate_utf8 ("stdout", &local_stdout_buf,
1791 if (!communicate_result_validate_utf8 ("stderr", &local_stderr_buf,
1798 g_object_unref (result);
1800 if (ret && stdout_buf != NULL)
1801 *stdout_buf = g_steal_pointer (&local_stdout_buf);
1802 if (ret && stderr_buf != NULL)
1803 *stderr_buf = g_steal_pointer (&local_stderr_buf);
1805 g_free (local_stderr_buf);
1806 g_free (local_stdout_buf);