gresourcefile: simplify path canonicalization
[glib.git] / gio / gsubprocess.c
blob18de30e55811b1e6d6d6e1953ba8cad38e8b2114
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2012, 2013 Red Hat, Inc.
4 * Copyright © 2012, 2013 Canonical Limited
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * See the included COPYING file for more information.
13 * Authors: Colin Walters <walters@verbum.org>
14 * Ryan Lortie <desrt@desrt.ca>
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 int errsv;
203 flags &= (~FD_CLOEXEC);
206 result = fcntl (fd, F_SETFD, flags);
207 errsv = errno;
209 while (result == -1 && errsv == EINTR);
213 static int
214 dupfd_cloexec (int parent_fd)
216 int fd, errsv;
217 #ifdef F_DUPFD_CLOEXEC
220 fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
221 errsv = errno;
223 while (fd == -1 && errsv == EINTR);
224 #else
225 /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
226 * https://bugzilla.gnome.org/show_bug.cgi?id=710962
228 int result, flags;
231 fd = fcntl (parent_fd, F_DUPFD, 3);
232 errsv = errno;
234 while (fd == -1 && errsv == EINTR);
235 flags = fcntl (fd, F_GETFD, 0);
236 if (flags != -1)
238 flags |= FD_CLOEXEC;
241 result = fcntl (fd, F_SETFD, flags);
242 errsv = errno;
244 while (result == -1 && errsv == EINTR);
246 #endif
247 return fd;
251 * Based on code derived from
252 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
253 * used under the LGPLv2+ with permission from author.
255 static void
256 child_setup (gpointer user_data)
258 ChildData *child_data = user_data;
259 gint i;
260 gint result;
261 int errsv;
263 /* We're on the child side now. "Rename" the file descriptors in
264 * child_data.fds[] to stdin/stdout/stderr.
266 * We don't close the originals. It's possible that the originals
267 * should not be closed and if they should be closed then they should
268 * have been created O_CLOEXEC.
270 for (i = 0; i < 3; i++)
271 if (child_data->fds[i] != -1 && child_data->fds[i] != i)
275 result = dup2 (child_data->fds[i], i);
276 errsv = errno;
278 while (result == -1 && errsv == EINTR);
281 /* Basic fd assignments we can just unset FD_CLOEXEC */
282 if (child_data->basic_fd_assignments)
284 for (i = 0; i < child_data->basic_fd_assignments->len; i++)
286 gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
288 unset_cloexec (fd);
292 /* If we're doing remapping fd assignments, we need to handle
293 * the case where the user has specified e.g.:
294 * 5 -> 4, 4 -> 6
296 * We do this by duping the source fds temporarily.
298 if (child_data->needdup_fd_assignments)
300 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
302 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
303 gint new_parent_fd;
305 new_parent_fd = dupfd_cloexec (parent_fd);
307 g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
309 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
311 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
312 gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
314 if (parent_fd == child_fd)
316 unset_cloexec (parent_fd);
318 else
322 result = dup2 (parent_fd, child_fd);
323 errsv = errno;
325 while (result == -1 && errsv == EINTR);
326 (void) close (parent_fd);
331 if (child_data->child_setup_func)
332 child_data->child_setup_func (child_data->child_setup_data);
334 #endif
336 static GInputStream *
337 platform_input_stream_from_spawn_fd (gint fd)
339 if (fd < 0)
340 return NULL;
342 #ifdef G_OS_UNIX
343 return g_unix_input_stream_new (fd, TRUE);
344 #else
345 return g_win32_input_stream_new_from_fd (fd, TRUE);
346 #endif
349 static GOutputStream *
350 platform_output_stream_from_spawn_fd (gint fd)
352 if (fd < 0)
353 return NULL;
355 #ifdef G_OS_UNIX
356 return g_unix_output_stream_new (fd, TRUE);
357 #else
358 return g_win32_output_stream_new_from_fd (fd, TRUE);
359 #endif
362 #ifdef G_OS_UNIX
363 static gint
364 unix_open_file (const char *filename,
365 gint mode,
366 GError **error)
368 gint my_fd;
370 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
372 /* If we return -1 we should also set the error */
373 if (my_fd < 0)
375 gint saved_errno = errno;
376 char *display_name;
378 display_name = g_filename_display_name (filename);
379 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
380 _("Error opening file “%s”: %s"), display_name,
381 g_strerror (saved_errno));
382 g_free (display_name);
383 /* fall through... */
385 #ifndef HAVE_O_CLOEXEC
386 else
387 fcntl (my_fd, F_SETFD, FD_CLOEXEC);
388 #endif
390 return my_fd;
392 #endif
394 static void
395 g_subprocess_set_property (GObject *object,
396 guint prop_id,
397 const GValue *value,
398 GParamSpec *pspec)
400 GSubprocess *self = G_SUBPROCESS (object);
402 switch (prop_id)
404 case PROP_FLAGS:
405 self->flags = g_value_get_flags (value);
406 break;
408 case PROP_ARGV:
409 self->argv = g_value_dup_boxed (value);
410 break;
412 default:
413 g_assert_not_reached ();
417 static gboolean
418 g_subprocess_exited (GPid pid,
419 gint status,
420 gpointer user_data)
422 GSubprocess *self = user_data;
423 GSList *tasks;
425 g_assert (self->pid == pid);
427 g_mutex_lock (&self->pending_waits_lock);
428 self->status = status;
429 tasks = self->pending_waits;
430 self->pending_waits = NULL;
431 self->pid = 0;
432 g_mutex_unlock (&self->pending_waits_lock);
434 /* Signal anyone in g_subprocess_wait_async() to wake up now */
435 while (tasks)
437 g_task_return_boolean (tasks->data, TRUE);
438 g_object_unref (tasks->data);
439 tasks = g_slist_delete_link (tasks, tasks);
442 g_spawn_close_pid (pid);
444 return FALSE;
447 static gboolean
448 initable_init (GInitable *initable,
449 GCancellable *cancellable,
450 GError **error)
452 GSubprocess *self = G_SUBPROCESS (initable);
453 #ifdef G_OS_UNIX
454 ChildData child_data = { { -1, -1, -1 }, 0 };
455 #endif
456 gint *pipe_ptrs[3] = { NULL, NULL, NULL };
457 gint pipe_fds[3] = { -1, -1, -1 };
458 gint close_fds[3] = { -1, -1, -1 };
459 GSpawnFlags spawn_flags = 0;
460 gboolean success = FALSE;
461 gint i;
463 /* this is a programmer error */
464 if (!self->argv || !self->argv[0] || !self->argv[0][0])
465 return FALSE;
467 if (g_cancellable_set_error_if_cancelled (cancellable, error))
468 return FALSE;
470 /* We must setup the three fds that will end up in the child as stdin,
471 * stdout and stderr.
473 * First, stdin.
475 if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
476 spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
477 else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
478 pipe_ptrs[0] = &pipe_fds[0];
479 #ifdef G_OS_UNIX
480 else if (self->launcher)
482 if (self->launcher->stdin_fd != -1)
483 child_data.fds[0] = self->launcher->stdin_fd;
484 else if (self->launcher->stdin_path != NULL)
486 child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
487 if (child_data.fds[0] == -1)
488 goto out;
491 #endif
493 /* Next, stdout. */
494 if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
495 spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
496 else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
497 pipe_ptrs[1] = &pipe_fds[1];
498 #ifdef G_OS_UNIX
499 else if (self->launcher)
501 if (self->launcher->stdout_fd != -1)
502 child_data.fds[1] = self->launcher->stdout_fd;
503 else if (self->launcher->stdout_path != NULL)
505 child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
506 if (child_data.fds[1] == -1)
507 goto out;
510 #endif
512 /* Finally, stderr. */
513 if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
514 spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
515 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
516 pipe_ptrs[2] = &pipe_fds[2];
517 #ifdef G_OS_UNIX
518 else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
519 /* This will work because stderr gets setup after stdout. */
520 child_data.fds[2] = 1;
521 else if (self->launcher)
523 if (self->launcher->stderr_fd != -1)
524 child_data.fds[2] = self->launcher->stderr_fd;
525 else if (self->launcher->stderr_path != NULL)
527 child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
528 if (child_data.fds[2] == -1)
529 goto out;
532 #endif
534 #ifdef G_OS_UNIX
535 if (self->launcher)
537 child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
538 child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
540 #endif
542 /* argv0 has no '/' in it? We better do a PATH lookup. */
543 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
545 if (self->launcher && self->launcher->path_from_envp)
546 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
547 else
548 spawn_flags |= G_SPAWN_SEARCH_PATH;
551 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
552 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
554 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
555 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
557 #ifdef G_OS_UNIX
558 child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
559 child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
560 #endif
562 success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
563 self->argv,
564 self->launcher ? self->launcher->envp : NULL,
565 spawn_flags,
566 #ifdef G_OS_UNIX
567 child_setup, &child_data,
568 #else
569 NULL, NULL,
570 #endif
571 &self->pid,
572 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
573 error);
574 g_assert (success == (self->pid != 0));
577 guint64 identifier;
578 gint s;
580 #ifdef G_OS_WIN32
581 identifier = (guint64) GetProcessId (self->pid);
582 #else
583 identifier = (guint64) self->pid;
584 #endif
586 s = g_snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
587 g_assert (0 < s && s < sizeof self->identifier);
590 /* Start attempting to reap the child immediately */
591 if (success)
593 GMainContext *worker_context;
594 GSource *source;
596 worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
597 source = g_child_watch_source_new (self->pid);
598 g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
599 g_source_attach (source, worker_context);
600 g_source_unref (source);
603 #ifdef G_OS_UNIX
604 out:
605 #endif
606 /* we don't need this past init... */
607 self->launcher = NULL;
609 for (i = 0; i < 3; i++)
610 if (close_fds[i] != -1)
611 close (close_fds[i]);
613 self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
614 self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
615 self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
617 return success;
620 static void
621 g_subprocess_finalize (GObject *object)
623 GSubprocess *self = G_SUBPROCESS (object);
625 g_assert (self->pending_waits == NULL);
626 g_assert (self->pid == 0);
628 g_clear_object (&self->stdin_pipe);
629 g_clear_object (&self->stdout_pipe);
630 g_clear_object (&self->stderr_pipe);
631 g_strfreev (self->argv);
633 g_mutex_clear (&self->pending_waits_lock);
635 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
638 static void
639 g_subprocess_init (GSubprocess *self)
641 g_mutex_init (&self->pending_waits_lock);
644 static void
645 initable_iface_init (GInitableIface *initable_iface)
647 initable_iface->init = initable_init;
650 static void
651 g_subprocess_class_init (GSubprocessClass *class)
653 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
655 gobject_class->finalize = g_subprocess_finalize;
656 gobject_class->set_property = g_subprocess_set_property;
658 g_object_class_install_property (gobject_class, PROP_FLAGS,
659 g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
660 G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
661 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
662 g_object_class_install_property (gobject_class, PROP_ARGV,
663 g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
664 G_TYPE_STRV, G_PARAM_WRITABLE |
665 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
669 * g_subprocess_new: (skip)
670 * @flags: flags that define the behaviour of the subprocess
671 * @error: (nullable): return location for an error, or %NULL
672 * @argv0: first commandline argument to pass to the subprocess
673 * @...: more commandline arguments, followed by %NULL
675 * Create a new process with the given flags and varargs argument
676 * list. By default, matching the g_spawn_async() defaults, the
677 * child's stdin will be set to the system null device, and
678 * stdout/stderr will be inherited from the parent. You can use
679 * @flags to control this behavior.
681 * The argument list must be terminated with %NULL.
683 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
684 * will be set)
686 * Since: 2.40
688 GSubprocess *
689 g_subprocess_new (GSubprocessFlags flags,
690 GError **error,
691 const gchar *argv0,
692 ...)
694 GSubprocess *result;
695 GPtrArray *args;
696 const gchar *arg;
697 va_list ap;
699 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
700 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
702 args = g_ptr_array_new ();
704 va_start (ap, argv0);
705 g_ptr_array_add (args, (gchar *) argv0);
706 while ((arg = va_arg (ap, const gchar *)))
707 g_ptr_array_add (args, (gchar *) arg);
708 g_ptr_array_add (args, NULL);
709 va_end (ap);
711 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
713 g_ptr_array_free (args, TRUE);
715 return result;
719 * g_subprocess_newv: (rename-to g_subprocess_new)
720 * @argv: (array zero-terminated=1) (element-type filename): commandline arguments for the subprocess
721 * @flags: flags that define the behaviour of the subprocess
722 * @error: (nullable): return location for an error, or %NULL
724 * Create a new process with the given flags and argument list.
726 * The argument list is expected to be %NULL-terminated.
728 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
729 * will be set)
731 * Since: 2.40
733 GSubprocess *
734 g_subprocess_newv (const gchar * const *argv,
735 GSubprocessFlags flags,
736 GError **error)
738 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
740 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
741 "argv", argv,
742 "flags", flags,
743 NULL);
747 * g_subprocess_get_identifier:
748 * @subprocess: a #GSubprocess
750 * On UNIX, returns the process ID as a decimal string.
751 * On Windows, returns the result of GetProcessId() also as a string.
753 const gchar *
754 g_subprocess_get_identifier (GSubprocess *subprocess)
756 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
758 if (subprocess->pid)
759 return subprocess->identifier;
760 else
761 return NULL;
765 * g_subprocess_get_stdin_pipe:
766 * @subprocess: a #GSubprocess
768 * Gets the #GOutputStream that you can write to in order to give data
769 * to the stdin of @subprocess.
771 * The process must have been created with
772 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
774 * Returns: (transfer none): the stdout pipe
776 * Since: 2.40
778 GOutputStream *
779 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
781 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
782 g_return_val_if_fail (subprocess->stdin_pipe, NULL);
784 return subprocess->stdin_pipe;
788 * g_subprocess_get_stdout_pipe:
789 * @subprocess: a #GSubprocess
791 * Gets the #GInputStream from which to read the stdout output of
792 * @subprocess.
794 * The process must have been created with
795 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
797 * Returns: (transfer none): the stdout pipe
799 * Since: 2.40
801 GInputStream *
802 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
804 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
805 g_return_val_if_fail (subprocess->stdout_pipe, NULL);
807 return subprocess->stdout_pipe;
811 * g_subprocess_get_stderr_pipe:
812 * @subprocess: a #GSubprocess
814 * Gets the #GInputStream from which to read the stderr output of
815 * @subprocess.
817 * The process must have been created with
818 * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
820 * Returns: (transfer none): the stderr pipe
822 * Since: 2.40
824 GInputStream *
825 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
827 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
828 g_return_val_if_fail (subprocess->stderr_pipe, NULL);
830 return subprocess->stderr_pipe;
833 /* Remove the first list element containing @data, and return %TRUE. If no
834 * such element is found, return %FALSE. */
835 static gboolean
836 slist_remove_if_present (GSList **list,
837 gconstpointer data)
839 GSList *l, *prev;
841 for (l = *list, prev = NULL; l != NULL; prev = l, l = prev->next)
843 if (l->data == data)
845 if (prev != NULL)
846 prev->next = l->next;
847 else
848 *list = l->next;
850 g_slist_free_1 (l);
852 return TRUE;
856 return FALSE;
859 static void
860 g_subprocess_wait_cancelled (GCancellable *cancellable,
861 gpointer user_data)
863 GTask *task = user_data;
864 GSubprocess *self;
865 gboolean task_was_pending;
867 self = g_task_get_source_object (task);
869 g_mutex_lock (&self->pending_waits_lock);
870 task_was_pending = slist_remove_if_present (&self->pending_waits, task);
871 g_mutex_unlock (&self->pending_waits_lock);
873 if (task_was_pending)
875 g_task_return_boolean (task, FALSE);
876 g_object_unref (task); /* ref from pending_waits */
881 * g_subprocess_wait_async:
882 * @subprocess: a #GSubprocess
883 * @cancellable: a #GCancellable, or %NULL
884 * @callback: a #GAsyncReadyCallback to call when the operation is complete
885 * @user_data: user_data for @callback
887 * Wait for the subprocess to terminate.
889 * This is the asynchronous version of g_subprocess_wait().
891 * Since: 2.40
893 void
894 g_subprocess_wait_async (GSubprocess *subprocess,
895 GCancellable *cancellable,
896 GAsyncReadyCallback callback,
897 gpointer user_data)
899 GTask *task;
901 task = g_task_new (subprocess, cancellable, callback, user_data);
902 g_task_set_source_tag (task, g_subprocess_wait_async);
904 g_mutex_lock (&subprocess->pending_waits_lock);
905 if (subprocess->pid)
907 /* Only bother with cancellable if we're putting it in the list.
908 * If not, it's going to dispatch immediately anyway and we will
909 * see the cancellation in the _finish().
911 if (cancellable)
912 g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
914 subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
915 task = NULL;
917 g_mutex_unlock (&subprocess->pending_waits_lock);
919 /* If we still have task then it's because did_exit is already TRUE */
920 if (task != NULL)
922 g_task_return_boolean (task, TRUE);
923 g_object_unref (task);
928 * g_subprocess_wait_finish:
929 * @subprocess: a #GSubprocess
930 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
931 * @error: a pointer to a %NULL #GError, or %NULL
933 * Collects the result of a previous call to
934 * g_subprocess_wait_async().
936 * Returns: %TRUE if successful, or %FALSE with @error set
938 * Since: 2.40
940 gboolean
941 g_subprocess_wait_finish (GSubprocess *subprocess,
942 GAsyncResult *result,
943 GError **error)
945 return g_task_propagate_boolean (G_TASK (result), error);
948 /* Some generic helpers for emulating synchronous operations using async
949 * operations.
951 static void
952 g_subprocess_sync_setup (void)
954 g_main_context_push_thread_default (g_main_context_new ());
957 static void
958 g_subprocess_sync_done (GObject *source_object,
959 GAsyncResult *result,
960 gpointer user_data)
962 GAsyncResult **result_ptr = user_data;
964 *result_ptr = g_object_ref (result);
967 static void
968 g_subprocess_sync_complete (GAsyncResult **result)
970 GMainContext *context = g_main_context_get_thread_default ();
972 while (!*result)
973 g_main_context_iteration (context, TRUE);
975 g_main_context_pop_thread_default (context);
976 g_main_context_unref (context);
980 * g_subprocess_wait:
981 * @subprocess: a #GSubprocess
982 * @cancellable: a #GCancellable
983 * @error: a #GError
985 * Synchronously wait for the subprocess to terminate.
987 * After the process terminates you can query its exit status with
988 * functions such as g_subprocess_get_if_exited() and
989 * g_subprocess_get_exit_status().
991 * This function does not fail in the case of the subprocess having
992 * abnormal termination. See g_subprocess_wait_check() for that.
994 * Cancelling @cancellable doesn't kill the subprocess. Call
995 * g_subprocess_force_exit() if it is desirable.
997 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
999 * Since: 2.40
1001 gboolean
1002 g_subprocess_wait (GSubprocess *subprocess,
1003 GCancellable *cancellable,
1004 GError **error)
1006 GAsyncResult *result = NULL;
1007 gboolean success;
1009 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1011 /* Synchronous waits are actually the 'more difficult' case because we
1012 * need to deal with the possibility of cancellation. That more or
1013 * less implies that we need a main context (to dispatch either of the
1014 * possible reasons for the operation ending).
1016 * So we make one and then do this async...
1019 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1020 return FALSE;
1022 /* We can shortcut in the case that the process already quit (but only
1023 * after we checked the cancellable).
1025 if (subprocess->pid == 0)
1026 return TRUE;
1028 /* Otherwise, we need to do this the long way... */
1029 g_subprocess_sync_setup ();
1030 g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
1031 g_subprocess_sync_complete (&result);
1032 success = g_subprocess_wait_finish (subprocess, result, error);
1033 g_object_unref (result);
1035 return success;
1039 * g_subprocess_wait_check:
1040 * @subprocess: a #GSubprocess
1041 * @cancellable: a #GCancellable
1042 * @error: a #GError
1044 * Combines g_subprocess_wait() with g_spawn_check_exit_status().
1046 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
1047 * @cancellable was cancelled
1049 * Since: 2.40
1051 gboolean
1052 g_subprocess_wait_check (GSubprocess *subprocess,
1053 GCancellable *cancellable,
1054 GError **error)
1056 return g_subprocess_wait (subprocess, cancellable, error) &&
1057 g_spawn_check_exit_status (subprocess->status, error);
1061 * g_subprocess_wait_check_async:
1062 * @subprocess: a #GSubprocess
1063 * @cancellable: a #GCancellable, or %NULL
1064 * @callback: a #GAsyncReadyCallback to call when the operation is complete
1065 * @user_data: user_data for @callback
1067 * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
1069 * This is the asynchronous version of g_subprocess_wait_check().
1071 * Since: 2.40
1073 void
1074 g_subprocess_wait_check_async (GSubprocess *subprocess,
1075 GCancellable *cancellable,
1076 GAsyncReadyCallback callback,
1077 gpointer user_data)
1079 g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
1083 * g_subprocess_wait_check_finish:
1084 * @subprocess: a #GSubprocess
1085 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
1086 * @error: a pointer to a %NULL #GError, or %NULL
1088 * Collects the result of a previous call to
1089 * g_subprocess_wait_check_async().
1091 * Returns: %TRUE if successful, or %FALSE with @error set
1093 * Since: 2.40
1095 gboolean
1096 g_subprocess_wait_check_finish (GSubprocess *subprocess,
1097 GAsyncResult *result,
1098 GError **error)
1100 return g_subprocess_wait_finish (subprocess, result, error) &&
1101 g_spawn_check_exit_status (subprocess->status, error);
1104 #ifdef G_OS_UNIX
1105 typedef struct
1107 GSubprocess *subprocess;
1108 gint signalnum;
1109 } SignalRecord;
1111 static gboolean
1112 g_subprocess_actually_send_signal (gpointer user_data)
1114 SignalRecord *signal_record = user_data;
1116 /* The pid is set to zero from the worker thread as well, so we don't
1117 * need to take a lock in order to prevent it from changing under us.
1119 if (signal_record->subprocess->pid)
1120 kill (signal_record->subprocess->pid, signal_record->signalnum);
1122 g_object_unref (signal_record->subprocess);
1124 g_slice_free (SignalRecord, signal_record);
1126 return FALSE;
1129 static void
1130 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1131 gint signalnum)
1133 SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1135 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1137 /* This MUST be a lower priority than the priority that the child
1138 * watch source uses in initable_init().
1140 * Reaping processes, reporting the results back to GSubprocess and
1141 * sending signals is all done in the glib worker thread. We cannot
1142 * have a kill() done after the reap and before the report without
1143 * risking killing a process that's no longer there so the kill()
1144 * needs to have the lower priority.
1146 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1148 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1149 G_PRIORITY_HIGH_IDLE,
1150 g_subprocess_actually_send_signal,
1151 g_slice_dup (SignalRecord, &signal_record),
1152 NULL);
1156 * g_subprocess_send_signal:
1157 * @subprocess: a #GSubprocess
1158 * @signal_num: the signal number to send
1160 * Sends the UNIX signal @signal_num to the subprocess, if it is still
1161 * running.
1163 * This API is race-free. If the subprocess has terminated, it will not
1164 * be signalled.
1166 * This API is not available on Windows.
1168 * Since: 2.40
1170 void
1171 g_subprocess_send_signal (GSubprocess *subprocess,
1172 gint signal_num)
1174 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1176 g_subprocess_dispatch_signal (subprocess, signal_num);
1178 #endif
1181 * g_subprocess_force_exit:
1182 * @subprocess: a #GSubprocess
1184 * Use an operating-system specific method to attempt an immediate,
1185 * forceful termination of the process. There is no mechanism to
1186 * determine whether or not the request itself was successful;
1187 * however, you can use g_subprocess_wait() to monitor the status of
1188 * the process after calling this function.
1190 * On Unix, this function sends %SIGKILL.
1192 * Since: 2.40
1194 void
1195 g_subprocess_force_exit (GSubprocess *subprocess)
1197 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1199 #ifdef G_OS_UNIX
1200 g_subprocess_dispatch_signal (subprocess, SIGKILL);
1201 #else
1202 TerminateProcess (subprocess->pid, 1);
1203 #endif
1207 * g_subprocess_get_status:
1208 * @subprocess: a #GSubprocess
1210 * Gets the raw status code of the process, as from waitpid().
1212 * This value has no particular meaning, but it can be used with the
1213 * macros defined by the system headers such as WIFEXITED. It can also
1214 * be used with g_spawn_check_exit_status().
1216 * It is more likely that you want to use g_subprocess_get_if_exited()
1217 * followed by g_subprocess_get_exit_status().
1219 * It is an error to call this function before g_subprocess_wait() has
1220 * returned.
1222 * Returns: the (meaningless) waitpid() exit status from the kernel
1224 * Since: 2.40
1226 gint
1227 g_subprocess_get_status (GSubprocess *subprocess)
1229 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1230 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1232 return subprocess->status;
1236 * g_subprocess_get_successful:
1237 * @subprocess: a #GSubprocess
1239 * Checks if the process was "successful". A process is considered
1240 * successful if it exited cleanly with an exit status of 0, either by
1241 * way of the exit() system call or return from main().
1243 * It is an error to call this function before g_subprocess_wait() has
1244 * returned.
1246 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1248 * Since: 2.40
1250 gboolean
1251 g_subprocess_get_successful (GSubprocess *subprocess)
1253 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1254 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1256 #ifdef G_OS_UNIX
1257 return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1258 #else
1259 return subprocess->status == 0;
1260 #endif
1264 * g_subprocess_get_if_exited:
1265 * @subprocess: a #GSubprocess
1267 * Check if the given subprocess exited normally (ie: by way of exit()
1268 * or return from main()).
1270 * This is equivalent to the system WIFEXITED macro.
1272 * It is an error to call this function before g_subprocess_wait() has
1273 * returned.
1275 * Returns: %TRUE if the case of a normal exit
1277 * Since: 2.40
1279 gboolean
1280 g_subprocess_get_if_exited (GSubprocess *subprocess)
1282 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1283 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1285 #ifdef G_OS_UNIX
1286 return WIFEXITED (subprocess->status);
1287 #else
1288 return TRUE;
1289 #endif
1293 * g_subprocess_get_exit_status:
1294 * @subprocess: a #GSubprocess
1296 * Check the exit status of the subprocess, given that it exited
1297 * normally. This is the value passed to the exit() system call or the
1298 * return value from main.
1300 * This is equivalent to the system WEXITSTATUS macro.
1302 * It is an error to call this function before g_subprocess_wait() and
1303 * unless g_subprocess_get_if_exited() returned %TRUE.
1305 * Returns: the exit status
1307 * Since: 2.40
1309 gint
1310 g_subprocess_get_exit_status (GSubprocess *subprocess)
1312 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1313 g_return_val_if_fail (subprocess->pid == 0, 1);
1315 #ifdef G_OS_UNIX
1316 g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1318 return WEXITSTATUS (subprocess->status);
1319 #else
1320 return subprocess->status;
1321 #endif
1325 * g_subprocess_get_if_signaled:
1326 * @subprocess: a #GSubprocess
1328 * Check if the given subprocess terminated in response to a signal.
1330 * This is equivalent to the system WIFSIGNALED macro.
1332 * It is an error to call this function before g_subprocess_wait() has
1333 * returned.
1335 * Returns: %TRUE if the case of termination due to a signal
1337 * Since: 2.40
1339 gboolean
1340 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1342 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1343 g_return_val_if_fail (subprocess->pid == 0, FALSE);
1345 #ifdef G_OS_UNIX
1346 return WIFSIGNALED (subprocess->status);
1347 #else
1348 return FALSE;
1349 #endif
1353 * g_subprocess_get_term_sig:
1354 * @subprocess: a #GSubprocess
1356 * Get the signal number that caused the subprocess to terminate, given
1357 * that it terminated due to a signal.
1359 * This is equivalent to the system WTERMSIG macro.
1361 * It is an error to call this function before g_subprocess_wait() and
1362 * unless g_subprocess_get_if_signaled() returned %TRUE.
1364 * Returns: the signal causing termination
1366 * Since: 2.40
1368 gint
1369 g_subprocess_get_term_sig (GSubprocess *subprocess)
1371 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1372 g_return_val_if_fail (subprocess->pid == 0, 0);
1374 #ifdef G_OS_UNIX
1375 g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1377 return WTERMSIG (subprocess->status);
1378 #else
1379 g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1380 "g_subprocess_get_if_signaled() always returns FALSE...");
1381 return 0;
1382 #endif
1385 /*< private >*/
1386 void
1387 g_subprocess_set_launcher (GSubprocess *subprocess,
1388 GSubprocessLauncher *launcher)
1390 subprocess->launcher = launcher;
1394 /* g_subprocess_communicate implementation below:
1396 * This is a tough problem. We have to watch 5 things at the same time:
1398 * - writing to stdin made progress
1399 * - reading from stdout made progress
1400 * - reading from stderr made progress
1401 * - process terminated
1402 * - cancellable being cancelled by caller
1404 * We use a GMainContext for all of these (either as async function
1405 * calls or as a GSource (in the case of the cancellable). That way at
1406 * least we don't have to worry about threading.
1408 * For the sync case we use the usual trick of creating a private main
1409 * context and iterating it until completion.
1411 * It's very possible that the process will dump a lot of data to stdout
1412 * just before it quits, so we can easily have data to read from stdout
1413 * and see the process has terminated at the same time. We want to make
1414 * sure that we read all of the data from the pipes first, though, so we
1415 * do IO operations at a higher priority than the wait operation (which
1416 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1417 * multiple reads to get this data, the pipe() will always be polling
1418 * as ready and with the async result for the read at a higher priority,
1419 * the main context will not dispatch the completion for the wait().
1421 * We keep our own private GCancellable. In the event that any of the
1422 * above suffers from an error condition (including the user cancelling
1423 * their cancellable) we immediately dispatch the GTask with the error
1424 * result and fire our cancellable to cleanup any pending operations.
1425 * In the case that the error is that the user's cancellable was fired,
1426 * it's vaguely wasteful to report an error because GTask will handle
1427 * this automatically, so we just return FALSE.
1429 * We let each pending sub-operation take a ref on the GTask of the
1430 * communicate operation. We have to be careful that we don't report
1431 * the task completion more than once, though, so we keep a flag for
1432 * that.
1434 typedef struct
1436 const gchar *stdin_data;
1437 gsize stdin_length;
1438 gsize stdin_offset;
1440 gboolean add_nul;
1442 GInputStream *stdin_buf;
1443 GMemoryOutputStream *stdout_buf;
1444 GMemoryOutputStream *stderr_buf;
1446 GCancellable *cancellable;
1447 GSource *cancellable_source;
1449 guint outstanding_ops;
1450 gboolean reported_error;
1451 } CommunicateState;
1453 static void
1454 g_subprocess_communicate_made_progress (GObject *source_object,
1455 GAsyncResult *result,
1456 gpointer user_data)
1458 CommunicateState *state;
1459 GSubprocess *subprocess;
1460 GError *error = NULL;
1461 gpointer source;
1462 GTask *task;
1464 g_assert (source_object != NULL);
1466 task = user_data;
1467 subprocess = g_task_get_source_object (task);
1468 state = g_task_get_task_data (task);
1469 source = source_object;
1471 state->outstanding_ops--;
1473 if (source == subprocess->stdin_pipe ||
1474 source == state->stdout_buf ||
1475 source == state->stderr_buf)
1477 if (g_output_stream_splice_finish ((GOutputStream*) source, result, &error) == -1)
1478 goto out;
1480 if (source == state->stdout_buf ||
1481 source == state->stderr_buf)
1483 /* This is a memory stream, so it can't be cancelled or return
1484 * an error really.
1486 if (state->add_nul)
1488 gsize bytes_written;
1489 if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1490 NULL, &error))
1491 goto out;
1493 if (!g_output_stream_close (source, NULL, &error))
1494 goto out;
1497 else if (source == subprocess)
1499 (void) g_subprocess_wait_finish (subprocess, result, &error);
1501 else
1502 g_assert_not_reached ();
1504 out:
1505 if (error)
1507 /* Only report the first error we see.
1509 * We might be seeing an error as a result of the cancellation
1510 * done when the process quits.
1512 if (!state->reported_error)
1514 state->reported_error = TRUE;
1515 g_cancellable_cancel (state->cancellable);
1516 g_task_return_error (task, error);
1518 else
1519 g_error_free (error);
1521 else if (state->outstanding_ops == 0)
1523 g_task_return_boolean (task, TRUE);
1526 /* And drop the original ref */
1527 g_object_unref (task);
1530 static gboolean
1531 g_subprocess_communicate_cancelled (gpointer user_data)
1533 CommunicateState *state = user_data;
1535 g_cancellable_cancel (state->cancellable);
1537 return FALSE;
1540 static void
1541 g_subprocess_communicate_state_free (gpointer data)
1543 CommunicateState *state = data;
1545 g_clear_object (&state->cancellable);
1546 g_clear_object (&state->stdin_buf);
1547 g_clear_object (&state->stdout_buf);
1548 g_clear_object (&state->stderr_buf);
1550 if (state->cancellable_source)
1552 g_source_destroy (state->cancellable_source);
1553 g_source_unref (state->cancellable_source);
1556 g_slice_free (CommunicateState, state);
1559 static CommunicateState *
1560 g_subprocess_communicate_internal (GSubprocess *subprocess,
1561 gboolean add_nul,
1562 GBytes *stdin_buf,
1563 GCancellable *cancellable,
1564 GAsyncReadyCallback callback,
1565 gpointer user_data)
1567 CommunicateState *state;
1568 GTask *task;
1570 task = g_task_new (subprocess, cancellable, callback, user_data);
1571 g_task_set_source_tag (task, g_subprocess_communicate_internal);
1573 state = g_slice_new0 (CommunicateState);
1574 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1576 state->cancellable = g_cancellable_new ();
1577 state->add_nul = add_nul;
1579 if (cancellable)
1581 state->cancellable_source = g_cancellable_source_new (cancellable);
1582 /* No ref held here, but we unref the source from state's free function */
1583 g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1584 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1587 if (subprocess->stdin_pipe)
1589 g_assert (stdin_buf != NULL);
1590 state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1591 g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1592 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1593 G_PRIORITY_DEFAULT, state->cancellable,
1594 g_subprocess_communicate_made_progress, g_object_ref (task));
1595 state->outstanding_ops++;
1598 if (subprocess->stdout_pipe)
1600 state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1601 g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1602 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1603 G_PRIORITY_DEFAULT, state->cancellable,
1604 g_subprocess_communicate_made_progress, g_object_ref (task));
1605 state->outstanding_ops++;
1608 if (subprocess->stderr_pipe)
1610 state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1611 g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1612 G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1613 G_PRIORITY_DEFAULT, state->cancellable,
1614 g_subprocess_communicate_made_progress, g_object_ref (task));
1615 state->outstanding_ops++;
1618 g_subprocess_wait_async (subprocess, state->cancellable,
1619 g_subprocess_communicate_made_progress, g_object_ref (task));
1620 state->outstanding_ops++;
1622 g_object_unref (task);
1623 return state;
1627 * g_subprocess_communicate:
1628 * @subprocess: a #GSubprocess
1629 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1630 * @cancellable: a #GCancellable
1631 * @stdout_buf: (out): data read from the subprocess stdout
1632 * @stderr_buf: (out): data read from the subprocess stderr
1633 * @error: a pointer to a %NULL #GError pointer, or %NULL
1635 * Communicate with the subprocess until it terminates, and all input
1636 * and output has been completed.
1638 * If @stdin_buf is given, the subprocess must have been created with
1639 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1640 * stdin of the subprocess and the pipe is closed (ie: EOF).
1642 * At the same time (as not to cause blocking when dealing with large
1643 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1644 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1645 * streams. The data that was read is returned in @stdout and/or
1646 * the @stderr.
1648 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1649 * @stdout_buf will contain the data read from stdout. Otherwise, for
1650 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1651 * @stdout_buf will be set to %NULL. Similar provisions apply to
1652 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1654 * As usual, any output variable may be given as %NULL to ignore it.
1656 * If you desire the stdout and stderr data to be interleaved, create
1657 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1658 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1659 * in @stdout_buf and @stderr_buf will be set to %NULL.
1661 * In case of any error (including cancellation), %FALSE will be
1662 * returned with @error set. Some or all of the stdin data may have
1663 * been written. Any stdout or stderr data that has been read will be
1664 * discarded. None of the out variables (aside from @error) will have
1665 * been set to anything in particular and should not be inspected.
1667 * In the case that %TRUE is returned, the subprocess has exited and the
1668 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1669 * g_subprocess_get_exit_status()) may be used.
1671 * You should not attempt to use any of the subprocess pipes after
1672 * starting this function, since they may be left in strange states,
1673 * even if the operation was cancelled. You should especially not
1674 * attempt to interact with the pipes while the operation is in progress
1675 * (either from another thread or if using the asynchronous version).
1677 * Returns: %TRUE if successful
1679 * Since: 2.40
1681 gboolean
1682 g_subprocess_communicate (GSubprocess *subprocess,
1683 GBytes *stdin_buf,
1684 GCancellable *cancellable,
1685 GBytes **stdout_buf,
1686 GBytes **stderr_buf,
1687 GError **error)
1689 GAsyncResult *result = NULL;
1690 gboolean success;
1692 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1693 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1694 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1695 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1697 g_subprocess_sync_setup ();
1698 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1699 g_subprocess_sync_done, &result);
1700 g_subprocess_sync_complete (&result);
1701 success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1702 g_object_unref (result);
1704 return success;
1708 * g_subprocess_communicate_async:
1709 * @subprocess: Self
1710 * @stdin_buf: (nullable): Input data, or %NULL
1711 * @cancellable: (nullable): Cancellable
1712 * @callback: Callback
1713 * @user_data: User data
1715 * Asynchronous version of g_subprocess_communicate(). Complete
1716 * invocation with g_subprocess_communicate_finish().
1718 void
1719 g_subprocess_communicate_async (GSubprocess *subprocess,
1720 GBytes *stdin_buf,
1721 GCancellable *cancellable,
1722 GAsyncReadyCallback callback,
1723 gpointer user_data)
1725 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1726 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1727 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1729 g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1733 * g_subprocess_communicate_finish:
1734 * @subprocess: Self
1735 * @result: Result
1736 * @stdout_buf: (out): Return location for stdout data
1737 * @stderr_buf: (out): Return location for stderr data
1738 * @error: Error
1740 * Complete an invocation of g_subprocess_communicate_async().
1742 gboolean
1743 g_subprocess_communicate_finish (GSubprocess *subprocess,
1744 GAsyncResult *result,
1745 GBytes **stdout_buf,
1746 GBytes **stderr_buf,
1747 GError **error)
1749 gboolean success;
1750 CommunicateState *state;
1752 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1753 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1754 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1756 g_object_ref (result);
1758 state = g_task_get_task_data ((GTask*)result);
1759 success = g_task_propagate_boolean ((GTask*)result, error);
1761 if (success)
1763 if (stdout_buf)
1764 *stdout_buf = g_memory_output_stream_steal_as_bytes (state->stdout_buf);
1765 if (stderr_buf)
1766 *stderr_buf = g_memory_output_stream_steal_as_bytes (state->stderr_buf);
1769 g_object_unref (result);
1770 return success;
1774 * g_subprocess_communicate_utf8:
1775 * @subprocess: a #GSubprocess
1776 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
1777 * @cancellable: a #GCancellable
1778 * @stdout_buf: (out): data read from the subprocess stdout
1779 * @stderr_buf: (out): data read from the subprocess stderr
1780 * @error: a pointer to a %NULL #GError pointer, or %NULL
1782 * Like g_subprocess_communicate(), but validates the output of the
1783 * process as UTF-8, and returns it as a regular NUL terminated string.
1785 gboolean
1786 g_subprocess_communicate_utf8 (GSubprocess *subprocess,
1787 const char *stdin_buf,
1788 GCancellable *cancellable,
1789 char **stdout_buf,
1790 char **stderr_buf,
1791 GError **error)
1793 GAsyncResult *result = NULL;
1794 gboolean success;
1795 GBytes *stdin_bytes;
1796 size_t stdin_buf_len = 0;
1798 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1799 g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1800 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1801 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1803 if (stdin_buf != NULL)
1804 stdin_buf_len = strlen (stdin_buf);
1805 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1807 g_subprocess_sync_setup ();
1808 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1809 g_subprocess_sync_done, &result);
1810 g_subprocess_sync_complete (&result);
1811 success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1812 g_object_unref (result);
1814 g_bytes_unref (stdin_bytes);
1815 return success;
1819 * g_subprocess_communicate_utf8_async:
1820 * @subprocess: Self
1821 * @stdin_buf: (nullable): Input data, or %NULL
1822 * @cancellable: Cancellable
1823 * @callback: Callback
1824 * @user_data: User data
1826 * Asynchronous version of g_subprocess_communicate_utf8(). Complete
1827 * invocation with g_subprocess_communicate_utf8_finish().
1829 void
1830 g_subprocess_communicate_utf8_async (GSubprocess *subprocess,
1831 const char *stdin_buf,
1832 GCancellable *cancellable,
1833 GAsyncReadyCallback callback,
1834 gpointer user_data)
1836 GBytes *stdin_bytes;
1837 size_t stdin_buf_len = 0;
1839 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1840 g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1841 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1843 if (stdin_buf != NULL)
1844 stdin_buf_len = strlen (stdin_buf);
1845 stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
1847 g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1849 g_bytes_unref (stdin_bytes);
1852 static gboolean
1853 communicate_result_validate_utf8 (const char *stream_name,
1854 char **return_location,
1855 GMemoryOutputStream *buffer,
1856 GError **error)
1858 if (return_location == NULL)
1859 return TRUE;
1861 if (buffer)
1863 const char *end;
1864 *return_location = g_memory_output_stream_steal_data (buffer);
1865 if (!g_utf8_validate (*return_location, -1, &end))
1867 g_free (*return_location);
1868 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1869 "Invalid UTF-8 in child %s at offset %lu",
1870 stream_name,
1871 (unsigned long) (end - *return_location));
1872 return FALSE;
1875 else
1876 *return_location = NULL;
1878 return TRUE;
1882 * g_subprocess_communicate_utf8_finish:
1883 * @subprocess: Self
1884 * @result: Result
1885 * @stdout_buf: (out): Return location for stdout data
1886 * @stderr_buf: (out): Return location for stderr data
1887 * @error: Error
1889 * Complete an invocation of g_subprocess_communicate_utf8_async().
1891 gboolean
1892 g_subprocess_communicate_utf8_finish (GSubprocess *subprocess,
1893 GAsyncResult *result,
1894 char **stdout_buf,
1895 char **stderr_buf,
1896 GError **error)
1898 gboolean ret = FALSE;
1899 CommunicateState *state;
1901 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1902 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1903 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1905 g_object_ref (result);
1907 state = g_task_get_task_data ((GTask*)result);
1908 if (!g_task_propagate_boolean ((GTask*)result, error))
1909 goto out;
1911 /* TODO - validate UTF-8 while streaming, rather than all at once.
1913 if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1914 state->stdout_buf,
1915 error))
1916 goto out;
1917 if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1918 state->stderr_buf,
1919 error))
1920 goto out;
1922 ret = TRUE;
1923 out:
1924 g_object_unref (result);
1925 return ret;