gtestutils: Fix a typo in a documentation comment
[glib.git] / gio / gsubprocess.c
blob5fd535575cd0988dbd88aecf6ed5bffa6cc1213d
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>
17 /**
18 * SECTION:gsubprocess
19 * @title: GSubprocess
20 * @short_description: Child processes
21 * @include: gio/gio.h
22 * @see_also: #GSubprocessLauncher
24 * #GSubprocess allows the creation of and interaction with child
25 * processes.
27 * Processes can be communicated with using standard GIO-style APIs (ie:
28 * #GInputStream, #GOutputStream). There are GIO-style APIs to wait for
29 * process termination (ie: cancellable and with an asynchronous
30 * variant).
32 * There is an API to force a process to terminate, as well as a
33 * race-free API for sending UNIX signals to a subprocess.
35 * One major advantage that GIO brings over the core GLib library is
36 * comprehensive API for asynchronous I/O, such
37 * g_output_stream_splice_async(). This makes GSubprocess
38 * significantly more powerful and flexible than equivalent APIs in
39 * some other languages such as the `subprocess.py`
40 * included with Python. For example, using #GSubprocess one could
41 * create two child processes, reading standard output from the first,
42 * processing it, and writing to the input stream of the second, all
43 * without blocking the main loop.
45 * A powerful g_subprocess_communicate() API is provided similar to the
46 * `communicate()` method of `subprocess.py`. This enables very easy
47 * interaction with a subprocess that has been opened with pipes.
49 * #GSubprocess defaults to tight control over the file descriptors open
50 * in the child process, avoiding dangling-fd issues that are caused by
51 * a simple fork()/exec(). The only open file descriptors in the
52 * spawned process are ones that were explicitly specified by the
53 * #GSubprocess API (unless %G_SUBPROCESS_FLAGS_INHERIT_FDS was
54 * specified).
56 * #GSubprocess will quickly reap all child processes as they exit,
57 * avoiding "zombie processes" remaining around for long periods of
58 * time. g_subprocess_wait() can be used to wait for this to happen,
59 * but it will happen even without the call being explicitly made.
61 * As a matter of principle, #GSubprocess has no API that accepts
62 * shell-style space-separated strings. It will, however, match the
63 * typical shell behaviour of searching the PATH for executables that do
64 * not contain a directory separator in their name.
66 * #GSubprocess attempts to have a very simple API for most uses (ie:
67 * spawning a subprocess with arguments and support for most typical
68 * kinds of input and output redirection). See g_subprocess_new(). The
69 * #GSubprocessLauncher API is provided for more complicated cases
70 * (advanced types of redirection, environment variable manipulation,
71 * change of working directory, child setup functions, etc).
73 * A typical use of #GSubprocess will involve calling
74 * g_subprocess_new(), followed by g_subprocess_wait_async() or
75 * g_subprocess_wait(). After the process exits, the status can be
76 * checked using functions such as g_subprocess_get_if_exited() (which
77 * are similar to the familiar WIFEXITED-style POSIX macros).
79 * Since: 2.40
80 **/
82 #include "config.h"
84 #include "gsubprocess.h"
85 #include "gsubprocesslauncher-private.h"
86 #include "gasyncresult.h"
87 #include "giostream.h"
88 #include "gmemoryinputstream.h"
89 #include "glibintl.h"
90 #include "glib-private.h"
92 #include <string.h>
93 #ifdef G_OS_UNIX
94 #include <gio/gunixoutputstream.h>
95 #include <gio/gfiledescriptorbased.h>
96 #include <gio/gunixinputstream.h>
97 #include <gstdio.h>
98 #include <glib-unix.h>
99 #include <fcntl.h>
100 #endif
101 #ifdef G_OS_WIN32
102 #include <windows.h>
103 #include <io.h>
104 #include "giowin32-priv.h"
105 #endif
107 #ifndef O_BINARY
108 #define O_BINARY 0
109 #endif
111 #ifndef O_CLOEXEC
112 #define O_CLOEXEC 0
113 #else
114 #define HAVE_O_CLOEXEC 1
115 #endif
117 #define COMMUNICATE_READ_SIZE 4096
119 /* A GSubprocess can have two possible states: running and not.
121 * These two states are reflected by the value of 'pid'. If it is
122 * non-zero then the process is running, with that pid.
124 * When a GSubprocess is first created with g_object_new() it is not
125 * running. When it is finalized, it is also not running.
127 * During initable_init(), if the g_spawn() is successful then we
128 * immediately register a child watch and take an extra ref on the
129 * subprocess. That reference doesn't drop until the child has quit,
130 * which is why finalize can only happen in the non-running state. In
131 * the event that the g_spawn() failed we will still be finalizing a
132 * non-running GSubprocess (before returning from g_subprocess_new())
133 * with NULL.
135 * We make extensive use of the glib worker thread to guarantee
136 * race-free operation. As with all child watches, glib calls waitpid()
137 * in the worker thread. It reports the child exiting to us via the
138 * worker thread (which means that we can do synchronous waits without
139 * running a separate loop). We also send signals to the child process
140 * via the worker thread so that we don't race with waitpid() and
141 * accidentally send a signal to an already-reaped child.
143 static void initable_iface_init (GInitableIface *initable_iface);
145 typedef GObjectClass GSubprocessClass;
147 struct _GSubprocess
149 GObject parent;
151 /* only used during construction */
152 GSubprocessLauncher *launcher;
153 GSubprocessFlags flags;
154 gchar **argv;
156 /* state tracking variables */
157 gchar identifier[24];
158 int status;
159 GPid pid;
161 /* list of GTask */
162 GMutex pending_waits_lock;
163 GSList *pending_waits;
165 /* These are the streams created if a pipe is requested via flags. */
166 GOutputStream *stdin_pipe;
167 GInputStream *stdout_pipe;
168 GInputStream *stderr_pipe;
171 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
172 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init));
174 enum
176 PROP_0,
177 PROP_FLAGS,
178 PROP_ARGV,
179 N_PROPS
182 #ifdef G_OS_UNIX
183 typedef struct
185 gint fds[3];
186 GSpawnChildSetupFunc child_setup_func;
187 gpointer child_setup_data;
188 GArray *basic_fd_assignments;
189 GArray *needdup_fd_assignments;
190 } ChildData;
192 static void
193 unset_cloexec (int fd)
195 int flags;
196 int result;
198 flags = fcntl (fd, F_GETFD, 0);
200 if (flags != -1)
202 flags &= (~FD_CLOEXEC);
204 result = fcntl (fd, F_SETFD, flags);
205 while (result == -1 && errno == EINTR);
209 static int
210 dupfd_cloexec (int parent_fd)
212 int fd;
213 #ifdef F_DUPFD_CLOEXEC
215 fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
216 while (fd == -1 && errno == EINTR);
217 #else
218 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
219 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
221 int result, flags;
223 fd = fcntl (parent_fd, F_DUPFD, 3);
224 while (fd == -1 && errno == EINTR);
225 flags = fcntl (fd, F_GETFD, 0);
226 if (flags != -1)
228 flags |= FD_CLOEXEC;
230 result = fcntl (fd, F_SETFD, flags);
231 while (result == -1 && errno == EINTR);
233 #endif
234 return fd;
238 * Based on code derived from
239 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
240 * used under the LGPLv2+ with permission from author.
242 static void
243 child_setup (gpointer user_data)
245 ChildData *child_data = user_data;
246 gint i;
247 gint result;
249 /* We're on the child side now. "Rename" the file descriptors in
250 * child_data.fds[] to stdin/stdout/stderr.
252 * We don't close the originals. It's possible that the originals
253 * should not be closed and if they should be closed then they should
254 * have been created O_CLOEXEC.
256 for (i = 0; i < 3; i++)
257 if (child_data->fds[i] != -1 && child_data->fds[i] != i)
260 result = dup2 (child_data->fds[i], i);
261 while (result == -1 && errno == EINTR);
264 /* Basic fd assignments we can just unset FD_CLOEXEC */
265 if (child_data->basic_fd_assignments)
267 for (i = 0; i < child_data->basic_fd_assignments->len; i++)
269 gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
271 unset_cloexec (fd);
275 /* If we're doing remapping fd assignments, we need to handle
276 * the case where the user has specified e.g.:
277 * 5 -> 4, 4 -> 6
279 * We do this by duping the source fds temporarily.
281 if (child_data->needdup_fd_assignments)
283 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
285 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
286 gint new_parent_fd;
288 new_parent_fd = dupfd_cloexec (parent_fd);
290 g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
292 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
294 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
295 gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
297 if (parent_fd == child_fd)
299 unset_cloexec (parent_fd);
301 else
304 result = dup2 (parent_fd, child_fd);
305 while (result == -1 && errno == EINTR);
306 (void) close (parent_fd);
311 if (child_data->child_setup_func)
312 child_data->child_setup_func (child_data->child_setup_data);
314 #endif
316 static GInputStream *
317 platform_input_stream_from_spawn_fd (gint fd)
319 if (fd < 0)
320 return NULL;
322 #ifdef G_OS_UNIX
323 return g_unix_input_stream_new (fd, TRUE);
324 #else
325 return g_win32_input_stream_new_from_fd (fd, TRUE);
326 #endif
329 static GOutputStream *
330 platform_output_stream_from_spawn_fd (gint fd)
332 if (fd < 0)
333 return NULL;
335 #ifdef G_OS_UNIX
336 return g_unix_output_stream_new (fd, TRUE);
337 #else
338 return g_win32_output_stream_new_from_fd (fd, TRUE);
339 #endif
342 #ifdef G_OS_UNIX
343 static gint
344 unix_open_file (const char *filename,
345 gint mode,
346 GError **error)
348 gint my_fd;
350 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
352 /* If we return -1 we should also set the error */
353 if (my_fd < 0)
355 gint saved_errno = errno;
356 char *display_name;
358 display_name = g_filename_display_name (filename);
359 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
360 _("Error opening file “%s”: %s"), display_name,
361 g_strerror (saved_errno));
362 g_free (display_name);
363 /* fall through... */
365 #ifndef HAVE_O_CLOEXEC
366 else
367 fcntl (my_fd, F_SETFD, FD_CLOEXEC);
368 #endif
370 return my_fd;
372 #endif
374 static void
375 g_subprocess_set_property (GObject *object,
376 guint prop_id,
377 const GValue *value,
378 GParamSpec *pspec)
380 GSubprocess *self = G_SUBPROCESS (object);
382 switch (prop_id)
384 case PROP_FLAGS:
385 self->flags = g_value_get_flags (value);
386 break;
388 case PROP_ARGV:
389 self->argv = g_value_dup_boxed (value);
390 break;
392 default:
393 g_assert_not_reached ();
397 static gboolean
398 g_subprocess_exited (GPid pid,
399 gint status,
400 gpointer user_data)
402 GSubprocess *self = user_data;
403 GSList *tasks;
405 g_assert (self->pid == pid);
407 g_mutex_lock (&self->pending_waits_lock);
408 self->status = status;
409 tasks = self->pending_waits;
410 self->pending_waits = NULL;
411 self->pid = 0;
412 g_mutex_unlock (&self->pending_waits_lock);
414 /* Signal anyone in g_subprocess_wait_async() to wake up now */
415 while (tasks)
417 g_task_return_boolean (tasks->data, TRUE);
418 g_object_unref (tasks->data);
419 tasks = g_slist_delete_link (tasks, tasks);
422 g_spawn_close_pid (pid);
424 return FALSE;
427 static gboolean
428 initable_init (GInitable *initable,
429 GCancellable *cancellable,
430 GError **error)
432 GSubprocess *self = G_SUBPROCESS (initable);
433 #ifdef G_OS_UNIX
434 ChildData child_data = { { -1, -1, -1 }, 0 };
435 #endif
436 gint *pipe_ptrs[3] = { NULL, NULL, NULL };
437 gint pipe_fds[3] = { -1, -1, -1 };
438 gint close_fds[3] = { -1, -1, -1 };
439 GSpawnFlags spawn_flags = 0;
440 gboolean success = FALSE;
441 gint i;
443 /* this is a programmer error */
444 if (!self->argv || !self->argv[0] || !self->argv[0][0])
445 return FALSE;
447 if (g_cancellable_set_error_if_cancelled (cancellable, error))
448 return FALSE;
450 /* We must setup the three fds that will end up in the child as stdin,
451 * stdout and stderr.
453 * First, stdin.
455 if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
456 spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
457 else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
458 pipe_ptrs[0] = &pipe_fds[0];
459 #ifdef G_OS_UNIX
460 else if (self->launcher)
462 if (self->launcher->stdin_fd != -1)
463 child_data.fds[0] = self->launcher->stdin_fd;
464 else if (self->launcher->stdin_path != NULL)
466 child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
467 if (child_data.fds[0] == -1)
468 goto out;
471 #endif
473 /* Next, stdout. */
474 if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
475 spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
476 else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
477 pipe_ptrs[1] = &pipe_fds[1];
478 #ifdef G_OS_UNIX
479 else if (self->launcher)
481 if (self->launcher->stdout_fd != -1)
482 child_data.fds[1] = self->launcher->stdout_fd;
483 else if (self->launcher->stdout_path != NULL)
485 child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
486 if (child_data.fds[1] == -1)
487 goto out;
490 #endif
492 /* Finally, stderr. */
493 if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
494 spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
495 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
496 pipe_ptrs[2] = &pipe_fds[2];
497 #ifdef G_OS_UNIX
498 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
499 /* This will work because stderr gets setup after stdout. */
500 child_data.fds[2] = 1;
501 else if (self->launcher)
503 if (self->launcher->stderr_fd != -1)
504 child_data.fds[2] = self->launcher->stderr_fd;
505 else if (self->launcher->stderr_path != NULL)
507 child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
508 if (child_data.fds[2] == -1)
509 goto out;
512 #endif
514 #ifdef G_OS_UNIX
515 if (self->launcher)
517 child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
518 child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
520 #endif
522 /* argv0 has no '/' in it? We better do a PATH lookup. */
523 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
525 if (self->launcher && self->launcher->path_from_envp)
526 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
527 else
528 spawn_flags |= G_SPAWN_SEARCH_PATH;
531 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
532 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
534 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
535 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
537 #ifdef G_OS_UNIX
538 child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
539 child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
540 #endif
542 success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
543 self->argv,
544 self->launcher ? self->launcher->envp : NULL,
545 spawn_flags,
546 #ifdef G_OS_UNIX
547 child_setup, &child_data,
548 #else
549 NULL, NULL,
550 #endif
551 &self->pid,
552 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
553 error);
554 g_assert (success == (self->pid != 0));
557 guint64 identifier;
558 gint s;
560 #ifdef G_OS_WIN32
561 identifier = (guint64) GetProcessId (self->pid);
562 #else
563 identifier = (guint64) self->pid;
564 #endif
566 s = g_snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
567 g_assert (0 < s && s < sizeof self->identifier);
570 /* Start attempting to reap the child immediately */
571 if (success)
573 GMainContext *worker_context;
574 GSource *source;
576 worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
577 source = g_child_watch_source_new (self->pid);
578 g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
579 g_source_attach (source, worker_context);
580 g_source_unref (source);
583 #ifdef G_OS_UNIX
584 out:
585 #endif
586 /* we don't need this past init... */
587 self->launcher = NULL;
589 for (i = 0; i < 3; i++)
590 if (close_fds[i] != -1)
591 close (close_fds[i]);
593 self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
594 self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
595 self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
597 return success;
600 static void
601 g_subprocess_finalize (GObject *object)
603 GSubprocess *self = G_SUBPROCESS (object);
605 g_assert (self->pending_waits == NULL);
606 g_assert (self->pid == 0);
608 g_clear_object (&self->stdin_pipe);
609 g_clear_object (&self->stdout_pipe);
610 g_clear_object (&self->stderr_pipe);
611 g_strfreev (self->argv);
613 g_mutex_clear (&self->pending_waits_lock);
615 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
618 static void
619 g_subprocess_init (GSubprocess *self)
621 g_mutex_init (&self->pending_waits_lock);
624 static void
625 initable_iface_init (GInitableIface *initable_iface)
627 initable_iface->init = initable_init;
630 static void
631 g_subprocess_class_init (GSubprocessClass *class)
633 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
635 gobject_class->finalize = g_subprocess_finalize;
636 gobject_class->set_property = g_subprocess_set_property;
638 g_object_class_install_property (gobject_class, PROP_FLAGS,
639 g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
640 G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
641 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
642 g_object_class_install_property (gobject_class, PROP_ARGV,
643 g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
644 G_TYPE_STRV, G_PARAM_WRITABLE |
645 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
649 * g_subprocess_new: (skip)
650 * @flags: flags that define the behaviour of the subprocess
651 * @error: (nullable): return location for an error, or %NULL
652 * @argv0: first commandline argument to pass to the subprocess
653 * @...: more commandline arguments, followed by %NULL
655 * Create a new process with the given flags and varargs argument
656 * list. By default, matching the g_spawn_async() defaults, the
657 * child's stdin will be set to the system null device, and
658 * stdout/stderr will be inherited from the parent. You can use
659 * @flags to control this behavior.
661 * The argument list must be terminated with %NULL.
663 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
664 * will be set)
666 * Since: 2.40
668 GSubprocess *
669 g_subprocess_new (GSubprocessFlags flags,
670 GError **error,
671 const gchar *argv0,
672 ...)
674 GSubprocess *result;
675 GPtrArray *args;
676 const gchar *arg;
677 va_list ap;
679 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
680 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
682 args = g_ptr_array_new ();
684 va_start (ap, argv0);
685 g_ptr_array_add (args, (gchar *) argv0);
686 while ((arg = va_arg (ap, const gchar *)))
687 g_ptr_array_add (args, (gchar *) arg);
688 g_ptr_array_add (args, NULL);
689 va_end (ap);
691 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
693 g_ptr_array_free (args, TRUE);
695 return result;
699 * g_subprocess_newv: (rename-to g_subprocess_new)
700 * @argv: (array zero-terminated=1) (element-type utf8): commandline arguments for the subprocess
701 * @flags: flags that define the behaviour of the subprocess
702 * @error: (nullable): return location for an error, or %NULL
704 * Create a new process with the given flags and argument list.
706 * The argument list is expected to be %NULL-terminated.
708 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
709 * will be set)
711 * Since: 2.40
713 GSubprocess *
714 g_subprocess_newv (const gchar * const *argv,
715 GSubprocessFlags flags,
716 GError **error)
718 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
720 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
721 "argv", argv,
722 "flags", flags,
723 NULL);
727 * g_subprocess_get_identifier:
728 * @subprocess: a #GSubprocess
730 * On UNIX, returns the process ID as a decimal string.
731 * On Windows, returns the result of GetProcessId() also as a string.
733 const gchar *
734 g_subprocess_get_identifier (GSubprocess *subprocess)
736 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
738 if (subprocess->pid)
739 return subprocess->identifier;
740 else
741 return NULL;
745 * g_subprocess_get_stdin_pipe:
746 * @subprocess: a #GSubprocess
748 * Gets the #GOutputStream that you can write to in order to give data
749 * to the stdin of @subprocess.
751 * The process must have been created with
752 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
754 * Returns: (transfer none): the stdout pipe
756 * Since: 2.40
758 GOutputStream *
759 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
761 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
762 g_return_val_if_fail (subprocess->stdin_pipe, NULL);
764 return subprocess->stdin_pipe;
768 * g_subprocess_get_stdout_pipe:
769 * @subprocess: a #GSubprocess
771 * Gets the #GInputStream from which to read the stdout output of
772 * @subprocess.
774 * The process must have been created with
775 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
777 * Returns: (transfer none): the stdout pipe
779 * Since: 2.40
781 GInputStream *
782 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
784 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
785 g_return_val_if_fail (subprocess->stdout_pipe, NULL);
787 return subprocess->stdout_pipe;
791 * g_subprocess_get_stderr_pipe:
792 * @subprocess: a #GSubprocess
794 * Gets the #GInputStream from which to read the stderr output of
795 * @subprocess.
797 * The process must have been created with
798 * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
800 * Returns: (transfer none): the stderr pipe
802 * Since: 2.40
804 GInputStream *
805 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
807 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
808 g_return_val_if_fail (subprocess->stderr_pipe, NULL);
810 return subprocess->stderr_pipe;
813 static void
814 g_subprocess_wait_cancelled (GCancellable *cancellable,
815 gpointer user_data)
817 GTask *task = user_data;
818 GSubprocess *self;
820 self = g_task_get_source_object (task);
822 g_mutex_lock (&self->pending_waits_lock);
823 self->pending_waits = g_slist_remove (self->pending_waits, task);
824 g_mutex_unlock (&self->pending_waits_lock);
826 g_task_return_boolean (task, FALSE);
827 g_object_unref (task);
831 * g_subprocess_wait_async:
832 * @subprocess: a #GSubprocess
833 * @cancellable: a #GCancellable, or %NULL
834 * @callback: a #GAsyncReadyCallback to call when the operation is complete
835 * @user_data: user_data for @callback
837 * Wait for the subprocess to terminate.
839 * This is the asynchronous version of g_subprocess_wait().
841 * Since: 2.40
843 void
844 g_subprocess_wait_async (GSubprocess *subprocess,
845 GCancellable *cancellable,
846 GAsyncReadyCallback callback,
847 gpointer user_data)
849 GTask *task;
851 task = g_task_new (subprocess, cancellable, callback, user_data);
852 g_task_set_source_tag (task, g_subprocess_wait_async);
854 g_mutex_lock (&subprocess->pending_waits_lock);
855 if (subprocess->pid)
857 /* Only bother with cancellable if we're putting it in the list.
858 * If not, it's going to dispatch immediately anyway and we will
859 * see the cancellation in the _finish().
861 if (cancellable)
862 g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
864 subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
865 task = NULL;
867 g_mutex_unlock (&subprocess->pending_waits_lock);
869 /* If we still have task then it's because did_exit is already TRUE */
870 if (task != NULL)
872 g_task_return_boolean (task, TRUE);
873 g_object_unref (task);
878 * g_subprocess_wait_finish:
879 * @subprocess: a #GSubprocess
880 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
881 * @error: a pointer to a %NULL #GError, or %NULL
883 * Collects the result of a previous call to
884 * g_subprocess_wait_async().
886 * Returns: %TRUE if successful, or %FALSE with @error set
888 * Since: 2.40
890 gboolean
891 g_subprocess_wait_finish (GSubprocess *subprocess,
892 GAsyncResult *result,
893 GError **error)
895 return g_task_propagate_boolean (G_TASK (result), error);
898 /* Some generic helpers for emulating synchronous operations using async
899 * operations.
901 static void
902 g_subprocess_sync_setup (void)
904 g_main_context_push_thread_default (g_main_context_new ());
907 static void
908 g_subprocess_sync_done (GObject *source_object,
909 GAsyncResult *result,
910 gpointer user_data)
912 GAsyncResult **result_ptr = user_data;
914 *result_ptr = g_object_ref (result);
917 static void
918 g_subprocess_sync_complete (GAsyncResult **result)
920 GMainContext *context = g_main_context_get_thread_default ();
922 while (!*result)
923 g_main_context_iteration (context, TRUE);
925 g_main_context_pop_thread_default (context);
926 g_main_context_unref (context);
930 * g_subprocess_wait:
931 * @subprocess: a #GSubprocess
932 * @cancellable: a #GCancellable
933 * @error: a #GError
935 * Synchronously wait for the subprocess to terminate.
937 * After the process terminates you can query its exit status with
938 * functions such as g_subprocess_get_if_exited() and
939 * g_subprocess_get_exit_status().
941 * This function does not fail in the case of the subprocess having
942 * abnormal termination. See g_subprocess_wait_check() for that.
944 * Cancelling @cancellable doesn't kill the subprocess. Call
945 * g_subprocess_force_exit() if it is desirable.
947 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
949 * Since: 2.40
951 gboolean
952 g_subprocess_wait (GSubprocess *subprocess,
953 GCancellable *cancellable,
954 GError **error)
956 GAsyncResult *result = NULL;
957 gboolean success;
959 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
961 /* Synchronous waits are actually the 'more difficult' case because we
962 * need to deal with the possibility of cancellation. That more or
963 * less implies that we need a main context (to dispatch either of the
964 * possible reasons for the operation ending).
966 * So we make one and then do this async...
969 if (g_cancellable_set_error_if_cancelled (cancellable, error))
970 return FALSE;
972 /* We can shortcut in the case that the process already quit (but only
973 * after we checked the cancellable).
975 if (subprocess->pid == 0)
976 return TRUE;
978 /* Otherwise, we need to do this the long way... */
979 g_subprocess_sync_setup ();
980 g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
981 g_subprocess_sync_complete (&result);
982 success = g_subprocess_wait_finish (subprocess, result, error);
983 g_object_unref (result);
985 return success;
989 * g_subprocess_wait_check:
990 * @subprocess: a #GSubprocess
991 * @cancellable: a #GCancellable
992 * @error: a #GError
994 * Combines g_subprocess_wait() with g_spawn_check_exit_status().
996 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
997 * @cancellable was cancelled
999 * Since: 2.40
1001 gboolean
1002 g_subprocess_wait_check (GSubprocess *subprocess,
1003 GCancellable *cancellable,
1004 GError **error)
1006 return g_subprocess_wait (subprocess, cancellable, error) &&
1007 g_spawn_check_exit_status (subprocess->status, error);
1011 * g_subprocess_wait_check_async:
1012 * @subprocess: a #GSubprocess
1013 * @cancellable: a #GCancellable, or %NULL
1014 * @callback: a #GAsyncReadyCallback to call when the operation is complete
1015 * @user_data: user_data for @callback
1017 * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
1019 * This is the asynchronous version of g_subprocess_wait_check().
1021 * Since: 2.40
1023 void
1024 g_subprocess_wait_check_async (GSubprocess *subprocess,
1025 GCancellable *cancellable,
1026 GAsyncReadyCallback callback,
1027 gpointer user_data)
1029 g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
1033 * g_subprocess_wait_check_finish:
1034 * @subprocess: a #GSubprocess
1035 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
1036 * @error: a pointer to a %NULL #GError, or %NULL
1038 * Collects the result of a previous call to
1039 * g_subprocess_wait_check_async().
1041 * Returns: %TRUE if successful, or %FALSE with @error set
1043 * Since: 2.40
1045 gboolean
1046 g_subprocess_wait_check_finish (GSubprocess *subprocess,
1047 GAsyncResult *result,
1048 GError **error)
1050 return g_subprocess_wait_finish (subprocess, result, error) &&
1051 g_spawn_check_exit_status (subprocess->status, error);
1054 #ifdef G_OS_UNIX
1055 typedef struct
1057 GSubprocess *subprocess;
1058 gint signalnum;
1059 } SignalRecord;
1061 static gboolean
1062 g_subprocess_actually_send_signal (gpointer user_data)
1064 SignalRecord *signal_record = user_data;
1066 /* The pid is set to zero from the worker thread as well, so we don't
1067 * need to take a lock in order to prevent it from changing under us.
1069 if (signal_record->subprocess->pid)
1070 kill (signal_record->subprocess->pid, signal_record->signalnum);
1072 g_object_unref (signal_record->subprocess);
1074 g_slice_free (SignalRecord, signal_record);
1076 return FALSE;
1079 static void
1080 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1081 gint signalnum)
1083 SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1085 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1087 /* This MUST be a lower priority than the priority that the child
1088 * watch source uses in initable_init().
1090 * Reaping processes, reporting the results back to GSubprocess and
1091 * sending signals is all done in the glib worker thread. We cannot
1092 * have a kill() done after the reap and before the report without
1093 * risking killing a process that's no longer there so the kill()
1094 * needs to have the lower priority.
1096 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1098 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1099 G_PRIORITY_HIGH_IDLE,
1100 g_subprocess_actually_send_signal,
1101 g_slice_dup (SignalRecord, &signal_record),
1102 NULL);
1106 * g_subprocess_send_signal:
1107 * @subprocess: a #GSubprocess
1108 * @signal_num: the signal number to send
1110 * Sends the UNIX signal @signal_num to the subprocess, if it is still
1111 * running.
1113 * This API is race-free. If the subprocess has terminated, it will not
1114 * be signalled.
1116 * This API is not available on Windows.
1118 * Since: 2.40
1120 void
1121 g_subprocess_send_signal (GSubprocess *subprocess,
1122 gint signal_num)
1124 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1126 g_subprocess_dispatch_signal (subprocess, signal_num);
1128 #endif
1131 * g_subprocess_force_exit:
1132 * @subprocess: a #GSubprocess
1134 * Use an operating-system specific method to attempt an immediate,
1135 * forceful termination of the process. There is no mechanism to
1136 * determine whether or not the request itself was successful;
1137 * however, you can use g_subprocess_wait() to monitor the status of
1138 * the process after calling this function.
1140 * On Unix, this function sends %SIGKILL.
1142 * Since: 2.40
1144 void
1145 g_subprocess_force_exit (GSubprocess *subprocess)
1147 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1149 #ifdef G_OS_UNIX
1150 g_subprocess_dispatch_signal (subprocess, SIGKILL);
1151 #else
1152 TerminateProcess (subprocess->pid, 1);
1153 #endif
1157 * g_subprocess_get_status:
1158 * @subprocess: a #GSubprocess
1160 * Gets the raw status code of the process, as from waitpid().
1162 * This value has no particular meaning, but it can be used with the
1163 * macros defined by the system headers such as WIFEXITED. It can also
1164 * be used with g_spawn_check_exit_status().
1166 * It is more likely that you want to use g_subprocess_get_if_exited()
1167 * followed by g_subprocess_get_exit_status().
1169 * It is an error to call this function before g_subprocess_wait() has
1170 * returned.
1172 * Returns: the (meaningless) waitpid() exit status from the kernel
1174 * Since: 2.40
1176 gint
1177 g_subprocess_get_status (GSubprocess *subprocess)
1179 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1180 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1182 return subprocess->status;
1186 * g_subprocess_get_successful:
1187 * @subprocess: a #GSubprocess
1189 * Checks if the process was "successful". A process is considered
1190 * successful if it exited cleanly with an exit status of 0, either by
1191 * way of the exit() system call or return from main().
1193 * It is an error to call this function before g_subprocess_wait() has
1194 * returned.
1196 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1198 * Since: 2.40
1200 gboolean
1201 g_subprocess_get_successful (GSubprocess *subprocess)
1203 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1204 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1206 #ifdef G_OS_UNIX
1207 return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1208 #else
1209 return subprocess->status == 0;
1210 #endif
1214 * g_subprocess_get_if_exited:
1215 * @subprocess: a #GSubprocess
1217 * Check if the given subprocess exited normally (ie: by way of exit()
1218 * or return from main()).
1220 * This is equivalent to the system WIFEXITED macro.
1222 * It is an error to call this function before g_subprocess_wait() has
1223 * returned.
1225 * Returns: %TRUE if the case of a normal exit
1227 * Since: 2.40
1229 gboolean
1230 g_subprocess_get_if_exited (GSubprocess *subprocess)
1232 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1233 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1235 #ifdef G_OS_UNIX
1236 return WIFEXITED (subprocess->status);
1237 #else
1238 return TRUE;
1239 #endif
1243 * g_subprocess_get_exit_status:
1244 * @subprocess: a #GSubprocess
1246 * Check the exit status of the subprocess, given that it exited
1247 * normally. This is the value passed to the exit() system call or the
1248 * return value from main.
1250 * This is equivalent to the system WEXITSTATUS macro.
1252 * It is an error to call this function before g_subprocess_wait() and
1253 * unless g_subprocess_get_if_exited() returned %TRUE.
1255 * Returns: the exit status
1257 * Since: 2.40
1259 gint
1260 g_subprocess_get_exit_status (GSubprocess *subprocess)
1262 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1263 g_return_val_if_fail (subprocess->pid == 0, 1);
1265 #ifdef G_OS_UNIX
1266 g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1268 return WEXITSTATUS (subprocess->status);
1269 #else
1270 return subprocess->status;
1271 #endif
1275 * g_subprocess_get_if_signaled:
1276 * @subprocess: a #GSubprocess
1278 * Check if the given subprocess terminated in response to a signal.
1280 * This is equivalent to the system WIFSIGNALED macro.
1282 * It is an error to call this function before g_subprocess_wait() has
1283 * returned.
1285 * Returns: %TRUE if the case of termination due to a signal
1287 * Since: 2.40
1289 gboolean
1290 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1292 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1293 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1295 #ifdef G_OS_UNIX
1296 return WIFSIGNALED (subprocess->status);
1297 #else
1298 return FALSE;
1299 #endif
1303 * g_subprocess_get_term_sig:
1304 * @subprocess: a #GSubprocess
1306 * Get the signal number that caused the subprocess to terminate, given
1307 * that it terminated due to a signal.
1309 * This is equivalent to the system WTERMSIG macro.
1311 * It is an error to call this function before g_subprocess_wait() and
1312 * unless g_subprocess_get_if_signaled() returned %TRUE.
1314 * Returns: the signal causing termination
1316 * Since: 2.40
1318 gint
1319 g_subprocess_get_term_sig (GSubprocess *subprocess)
1321 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1322 g_return_val_if_fail (subprocess->pid == 0, 0);
1324 #ifdef G_OS_UNIX
1325 g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1327 return WTERMSIG (subprocess->status);
1328 #else
1329 g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1330 "g_subprocess_get_if_signaled() always returns FALSE...");
1331 return 0;
1332 #endif
1335 /*< private >*/
1336 void
1337 g_subprocess_set_launcher (GSubprocess *subprocess,
1338 GSubprocessLauncher *launcher)
1340 subprocess->launcher = launcher;
1344 /* g_subprocess_communicate implementation below:
1346 * This is a tough problem. We have to watch 5 things at the same time:
1348 * - writing to stdin made progress
1349 * - reading from stdout made progress
1350 * - reading from stderr made progress
1351 * - process terminated
1352 * - cancellable being cancelled by caller
1354 * We use a GMainContext for all of these (either as async function
1355 * calls or as a GSource (in the case of the cancellable). That way at
1356 * least we don't have to worry about threading.
1358 * For the sync case we use the usual trick of creating a private main
1359 * context and iterating it until completion.
1361 * It's very possible that the process will dump a lot of data to stdout
1362 * just before it quits, so we can easily have data to read from stdout
1363 * and see the process has terminated at the same time. We want to make
1364 * sure that we read all of the data from the pipes first, though, so we
1365 * do IO operations at a higher priority than the wait operation (which
1366 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1367 * multiple reads to get this data, the pipe() will always be polling
1368 * as ready and with the async result for the read at a higher priority,
1369 * the main context will not dispatch the completion for the wait().
1371 * We keep our own private GCancellable. In the event that any of the
1372 * above suffers from an error condition (including the user cancelling
1373 * their cancellable) we immediately dispatch the GTask with the error
1374 * result and fire our cancellable to cleanup any pending operations.
1375 * In the case that the error is that the user's cancellable was fired,
1376 * it's vaguely wasteful to report an error because GTask will handle
1377 * this automatically, so we just return FALSE.
1379 * We let each pending sub-operation take a ref on the GTask of the
1380 * communicate operation. We have to be careful that we don't report
1381 * the task completion more than once, though, so we keep a flag for
1382 * that.
1384 typedef struct
1386 const gchar *stdin_data;
1387 gsize stdin_length;
1388 gsize stdin_offset;
1390 gboolean add_nul;
1392 GInputStream *stdin_buf;
1393 GMemoryOutputStream *stdout_buf;
1394 GMemoryOutputStream *stderr_buf;
1396 GCancellable *cancellable;
1397 GSource *cancellable_source;
1399 guint outstanding_ops;
1400 gboolean reported_error;
1401 } CommunicateState;
1403 static void
1404 g_subprocess_communicate_made_progress (GObject *source_object,
1405 GAsyncResult *result,
1406 gpointer user_data)
1408 CommunicateState *state;
1409 GSubprocess *subprocess;
1410 GError *error = NULL;
1411 gpointer source;
1412 GTask *task;
1414 g_assert (source_object != NULL);
1416 task = user_data;
1417 subprocess = g_task_get_source_object (task);
1418 state = g_task_get_task_data (task);
1419 source = source_object;
1421 state->outstanding_ops--;
1423 if (source == subprocess->stdin_pipe ||
1424 source == state->stdout_buf ||
1425 source == state->stderr_buf)
1427 if (g_output_stream_splice_finish ((GOutputStream*) source, result, &error) == -1)
1428 goto out;
1430 if (source == state->stdout_buf ||
1431 source == state->stderr_buf)
1433 /* This is a memory stream, so it can't be cancelled or return
1434 * an error really.
1436 if (state->add_nul)
1438 gsize bytes_written;
1439 if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1440 NULL, &error))
1441 goto out;
1443 if (!g_output_stream_close (source, NULL, &error))
1444 goto out;
1447 else if (source == subprocess)
1449 (void) g_subprocess_wait_finish (subprocess, result, &error);
1451 else
1452 g_assert_not_reached ();
1454 out:
1455 if (error)
1457 /* Only report the first error we see.
1459 * We might be seeing an error as a result of the cancellation
1460 * done when the process quits.
1462 if (!state->reported_error)
1464 state->reported_error = TRUE;
1465 g_cancellable_cancel (state->cancellable);
1466 g_task_return_error (task, error);
1468 else
1469 g_error_free (error);
1471 else if (state->outstanding_ops == 0)
1473 g_task_return_boolean (task, TRUE);
1476 /* And drop the original ref */
1477 g_object_unref (task);
1480 static gboolean
1481 g_subprocess_communicate_cancelled (gpointer user_data)
1483 CommunicateState *state = user_data;
1485 g_cancellable_cancel (state->cancellable);
1487 return FALSE;
1490 static void
1491 g_subprocess_communicate_state_free (gpointer data)
1493 CommunicateState *state = data;
1495 g_clear_object (&state->cancellable);
1496 g_clear_object (&state->stdin_buf);
1497 g_clear_object (&state->stdout_buf);
1498 g_clear_object (&state->stderr_buf);
1500 if (state->cancellable_source)
1502 if (!g_source_is_destroyed (state->cancellable_source))
1503 g_source_destroy (state->cancellable_source);
1504 g_source_unref (state->cancellable_source);
1507 g_slice_free (CommunicateState, state);
1510 static CommunicateState *
1511 g_subprocess_communicate_internal (GSubprocess *subprocess,
1512 gboolean add_nul,
1513 GBytes *stdin_buf,
1514 GCancellable *cancellable,
1515 GAsyncReadyCallback callback,
1516 gpointer user_data)
1518 CommunicateState *state;
1519 GTask *task;
1521 task = g_task_new (subprocess, cancellable, callback, user_data);
1522 g_task_set_source_tag (task, g_subprocess_communicate_internal);
1524 state = g_slice_new0 (CommunicateState);
1525 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1527 state->cancellable = g_cancellable_new ();
1528 state->add_nul = add_nul;
1530 if (cancellable)
1532 state->cancellable_source = g_cancellable_source_new (cancellable);
1533 /* No ref held here, but we unref the source from state's free function */
1534 g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1535 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1538 if (subprocess->stdin_pipe)
1540 g_assert (stdin_buf != NULL);
1541 state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1542 g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1543 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1544 G_PRIORITY_DEFAULT, state->cancellable,
1545 g_subprocess_communicate_made_progress, g_object_ref (task));
1546 state->outstanding_ops++;
1549 if (subprocess->stdout_pipe)
1551 state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1552 g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1553 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1554 G_PRIORITY_DEFAULT, state->cancellable,
1555 g_subprocess_communicate_made_progress, g_object_ref (task));
1556 state->outstanding_ops++;
1559 if (subprocess->stderr_pipe)
1561 state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1562 g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1563 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1564 G_PRIORITY_DEFAULT, state->cancellable,
1565 g_subprocess_communicate_made_progress, g_object_ref (task));
1566 state->outstanding_ops++;
1569 g_subprocess_wait_async (subprocess, state->cancellable,
1570 g_subprocess_communicate_made_progress, g_object_ref (task));
1571 state->outstanding_ops++;
1573 g_object_unref (task);
1574 return state;
1578 * g_subprocess_communicate:
1579 * @subprocess: a #GSubprocess
1580 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1581 * @cancellable: a #GCancellable
1582 * @stdout_buf: (out): data read from the subprocess stdout
1583 * @stderr_buf: (out): data read from the subprocess stderr
1584 * @error: a pointer to a %NULL #GError pointer, or %NULL
1586 * Communicate with the subprocess until it terminates, and all input
1587 * and output has been completed.
1589 * If @stdin_buf is given, the subprocess must have been created with
1590 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1591 * stdin of the subprocess and the pipe is closed (ie: EOF).
1593 * At the same time (as not to cause blocking when dealing with large
1594 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1595 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1596 * streams. The data that was read is returned in @stdout and/or
1597 * the @stderr.
1599 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1600 * @stdout_buf will contain the data read from stdout. Otherwise, for
1601 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1602 * @stdout_buf will be set to %NULL. Similar provisions apply to
1603 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1605 * As usual, any output variable may be given as %NULL to ignore it.
1607 * If you desire the stdout and stderr data to be interleaved, create
1608 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1609 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1610 * in @stdout_buf and @stderr_buf will be set to %NULL.
1612 * In case of any error (including cancellation), %FALSE will be
1613 * returned with @error set. Some or all of the stdin data may have
1614 * been written. Any stdout or stderr data that has been read will be
1615 * discarded. None of the out variables (aside from @error) will have
1616 * been set to anything in particular and should not be inspected.
1618 * In the case that %TRUE is returned, the subprocess has exited and the
1619 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1620 * g_subprocess_get_exit_status()) may be used.
1622 * You should not attempt to use any of the subprocess pipes after
1623 * starting this function, since they may be left in strange states,
1624 * even if the operation was cancelled. You should especially not
1625 * attempt to interact with the pipes while the operation is in progress
1626 * (either from another thread or if using the asynchronous version).
1628 * Returns: %TRUE if successful
1630 * Since: 2.40
1632 gboolean
1633 g_subprocess_communicate (GSubprocess *subprocess,
1634 GBytes *stdin_buf,
1635 GCancellable *cancellable,
1636 GBytes **stdout_buf,
1637 GBytes **stderr_buf,
1638 GError **error)
1640 GAsyncResult *result = NULL;
1641 gboolean success;
1643 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1644 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1645 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1646 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1648 g_subprocess_sync_setup ();
1649 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1650 g_subprocess_sync_done, &result);
1651 g_subprocess_sync_complete (&result);
1652 success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1653 g_object_unref (result);
1655 return success;
1659 * g_subprocess_communicate_async:
1660 * @subprocess: Self
1661 * @stdin_buf: (nullable): Input data, or %NULL
1662 * @cancellable: (nullable): Cancellable
1663 * @callback: Callback
1664 * @user_data: User data
1666 * Asynchronous version of g_subprocess_communicate(). Complete
1667 * invocation with g_subprocess_communicate_finish().
1669 void
1670 g_subprocess_communicate_async (GSubprocess *subprocess,
1671 GBytes *stdin_buf,
1672 GCancellable *cancellable,
1673 GAsyncReadyCallback callback,
1674 gpointer user_data)
1676 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1677 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1678 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1680 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1684 * g_subprocess_communicate_finish:
1685 * @subprocess: Self
1686 * @result: Result
1687 * @stdout_buf: (out): Return location for stdout data
1688 * @stderr_buf: (out): Return location for stderr data
1689 * @error: Error
1691 * Complete an invocation of g_subprocess_communicate_async().
1693 gboolean
1694 g_subprocess_communicate_finish (GSubprocess *subprocess,
1695 GAsyncResult *result,
1696 GBytes **stdout_buf,
1697 GBytes **stderr_buf,
1698 GError **error)
1700 gboolean success;
1701 CommunicateState *state;
1703 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1704 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1705 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1707 g_object_ref (result);
1709 state = g_task_get_task_data ((GTask*)result);
1710 success = g_task_propagate_boolean ((GTask*)result, error);
1712 if (success)
1714 if (stdout_buf)
1715 *stdout_buf = g_memory_output_stream_steal_as_bytes (state->stdout_buf);
1716 if (stderr_buf)
1717 *stderr_buf = g_memory_output_stream_steal_as_bytes (state->stderr_buf);
1720 g_object_unref (result);
1721 return success;
1725 * g_subprocess_communicate_utf8:
1726 * @subprocess: a #GSubprocess
1727 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1728 * @cancellable: a #GCancellable
1729 * @stdout_buf: (out): data read from the subprocess stdout
1730 * @stderr_buf: (out): data read from the subprocess stderr
1731 * @error: a pointer to a %NULL #GError pointer, or %NULL
1733 * Like g_subprocess_communicate(), but validates the output of the
1734 * process as UTF-8, and returns it as a regular NUL terminated string.
1736 gboolean
1737 g_subprocess_communicate_utf8 (GSubprocess *subprocess,
1738 const char *stdin_buf,
1739 GCancellable *cancellable,
1740 char **stdout_buf,
1741 char **stderr_buf,
1742 GError **error)
1744 GAsyncResult *result = NULL;
1745 gboolean success;
1746 GBytes *stdin_bytes;
1747 size_t stdin_buf_len = 0;
1749 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1750 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1751 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1752 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1754 if (stdin_buf != NULL)
1755 stdin_buf_len = strlen (stdin_buf);
1756 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1758 g_subprocess_sync_setup ();
1759 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1760 g_subprocess_sync_done, &result);
1761 g_subprocess_sync_complete (&result);
1762 success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1763 g_object_unref (result);
1765 g_bytes_unref (stdin_bytes);
1766 return success;
1770 * g_subprocess_communicate_utf8_async:
1771 * @subprocess: Self
1772 * @stdin_buf: (nullable): Input data, or %NULL
1773 * @cancellable: Cancellable
1774 * @callback: Callback
1775 * @user_data: User data
1777 * Asynchronous version of g_subprocess_communicate_utf8(). Complete
1778 * invocation with g_subprocess_communicate_utf8_finish().
1780 void
1781 g_subprocess_communicate_utf8_async (GSubprocess *subprocess,
1782 const char *stdin_buf,
1783 GCancellable *cancellable,
1784 GAsyncReadyCallback callback,
1785 gpointer user_data)
1787 GBytes *stdin_bytes;
1788 size_t stdin_buf_len = 0;
1790 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1791 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1792 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1794 if (stdin_buf != NULL)
1795 stdin_buf_len = strlen (stdin_buf);
1796 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1798 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1800 g_bytes_unref (stdin_bytes);
1803 static gboolean
1804 communicate_result_validate_utf8 (const char *stream_name,
1805 char **return_location,
1806 GMemoryOutputStream *buffer,
1807 GError **error)
1809 if (return_location == NULL)
1810 return TRUE;
1812 if (buffer)
1814 const char *end;
1815 *return_location = g_memory_output_stream_steal_data (buffer);
1816 if (!g_utf8_validate (*return_location, -1, &end))
1818 g_free (*return_location);
1819 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1820 "Invalid UTF-8 in child %s at offset %lu",
1821 stream_name,
1822 (unsigned long) (end - *return_location));
1823 return FALSE;
1826 else
1827 *return_location = NULL;
1829 return TRUE;
1833 * g_subprocess_communicate_utf8_finish:
1834 * @subprocess: Self
1835 * @result: Result
1836 * @stdout_buf: (out): Return location for stdout data
1837 * @stderr_buf: (out): Return location for stderr data
1838 * @error: Error
1840 * Complete an invocation of g_subprocess_communicate_utf8_async().
1842 gboolean
1843 g_subprocess_communicate_utf8_finish (GSubprocess *subprocess,
1844 GAsyncResult *result,
1845 char **stdout_buf,
1846 char **stderr_buf,
1847 GError **error)
1849 gboolean ret = FALSE;
1850 CommunicateState *state;
1852 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1853 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1854 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1856 g_object_ref (result);
1858 state = g_task_get_task_data ((GTask*)result);
1859 if (!g_task_propagate_boolean ((GTask*)result, error))
1860 goto out;
1862 /* TODO - validate UTF-8 while streaming, rather than all at once.
1864 if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1865 state->stdout_buf,
1866 error))
1867 goto out;
1868 if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1869 state->stderr_buf,
1870 error))
1871 goto out;
1873 ret = TRUE;
1874 out:
1875 g_object_unref (result);
1876 return ret;