Fixup GSubprocess documentation bits
[platform/upstream/glib.git] / gio / gsubprocess.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2012, 2013 Red Hat, Inc.
4  * Copyright © 2012, 2013 Canonical Limited
5  *
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.
10  *
11  * See the included COPYING file for more information.
12  *
13  * Authors: Colin Walters <walters@verbum.org>
14  *          Ryan Lortie <desrt@desrt.ca>
15  */
16
17 /**
18  * SECTION:gsubprocess
19  * @title: GSubprocess
20  * @short_description: Child processes
21  * @see_also: #GSubprocessLauncher
22  *
23  * #GSubprocess allows the creation of and interaction with child
24  * processes.
25  *
26  * Processes can be communicated with using standard GIO-style APIs (ie:
27  * #GInputStream, #GOutputStream).  There are GIO-style APIs to wait for
28  * process termination (ie: cancellable and with an asynchronous
29  * variant).
30  *
31  * There is an API to force a process to terminate, as well as a
32  * race-free API for sending UNIX signals to a subprocess.
33  *
34  * One major advantage that GIO brings over the core GLib library is
35  * comprehensive API for asynchronous I/O, such
36  * g_output_stream_splice_async().  This makes GSubprocess
37  * significantly more powerful and flexible than equivalent APIs in
38  * some other languages such as the <literal>subprocess.py</literal>
39  * included with Python.  For example, using #GSubprocess one could
40  * create two child processes, reading standard output from the first,
41  * processing it, and writing to the input stream of the second, all
42  * without blocking the main loop.
43  *
44  * A powerful g_subprocess_communicate() API is provided similar to the
45  * <literal>communicate()</literal> method of
46  * <literal>subprocess.py</literal>.  This enables very easy interaction
47  * with a subprocess that has been opened with pipes.
48  *
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).
55  *
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.
60  *
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.
65  *
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).
72  *
73  * A typical use of #GSubprocess will involve calling
74  * g_subprocess_new(), followed by g_subprocess_wait() or
75  * g_subprocess_wait_sync().  After the process exits, the status can be
76  * checked using functions such as g_subprocess_get_if_exited() (which
77  * are similar to the familiar WIFEXITED-style POSIX macros).
78  *
79  * Since: 2.40
80  **/
81
82 #include "config.h"
83
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"
91
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 #define _WIN32_WINNT 0x0500
103 #include <windows.h>
104 #include "giowin32-priv.h"
105 #endif
106
107 #ifndef O_BINARY
108 #define O_BINARY 0
109 #endif
110
111 #define COMMUNICATE_READ_SIZE 4096
112
113 /* A GSubprocess can have two possible states: running and not.
114  *
115  * These two states are reflected by the value of 'pid'.  If it is
116  * non-zero then the process is running, with that pid.
117  *
118  * When a GSubprocess is first created with g_object_new() it is not
119  * running.  When it is finalized, it is also not running.
120  *
121  * During initable_init(), if the g_spawn() is successful then we
122  * immediately register a child watch and take an extra ref on the
123  * subprocess.  That reference doesn't drop until the child has quit,
124  * which is why finalize can only happen in the non-running state.  In
125  * the event that the g_spawn() failed we will still be finalizing a
126  * non-running GSubprocess (before returning from g_subprocess_new())
127  * with NULL.
128  *
129  * We make extensive use of the glib worker thread to guarantee
130  * race-free operation.  As with all child watches, glib calls waitpid()
131  * in the worker thread.  It reports the child exiting to us via the
132  * worker thread (which means that we can do synchronous waits without
133  * running a separate loop).  We also send signals to the child process
134  * via the worker thread so that we don't race with waitpid() and
135  * accidentally send a signal to an already-reaped child.
136  */
137 static void initable_iface_init (GInitableIface         *initable_iface);
138
139 typedef GObjectClass GSubprocessClass;
140
141 struct _GSubprocess
142 {
143   GObject parent;
144
145   /* only used during construction */
146   GSubprocessLauncher *launcher;
147   GSubprocessFlags flags;
148   gchar **argv;
149
150   /* state tracking variables */
151   gchar identifier[24];
152   int status;
153   GPid pid;
154
155   /* list of GTask */
156   GMutex pending_waits_lock;
157   GSList *pending_waits;
158
159   /* These are the streams created if a pipe is requested via flags. */
160   GOutputStream *stdin_pipe;
161   GInputStream  *stdout_pipe;
162   GInputStream  *stderr_pipe;
163 };
164
165 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
166                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init));
167
168 enum
169 {
170   PROP_0,
171   PROP_FLAGS,
172   PROP_ARGV,
173   N_PROPS
174 };
175
176 typedef struct
177 {
178   gint                 fds[3];
179   GSpawnChildSetupFunc child_setup_func;
180   gpointer             child_setup_data;
181   GArray              *basic_fd_assignments;
182   GArray              *needdup_fd_assignments;
183 } ChildData;
184
185 static void
186 unset_cloexec (int fd)
187 {
188   int flags;
189   int result;
190
191   flags = fcntl (fd, F_GETFD, 0);
192
193   if (flags != -1)
194     {
195       flags &= (~FD_CLOEXEC);
196       do
197         result = fcntl (fd, F_SETFD, flags);
198       while (result == -1 && errno == EINTR);
199     }
200 }
201
202 /**
203  * Based on code derived from
204  * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
205  * used under the LGPLv2+ with permission from author.
206  */
207 static void
208 child_setup (gpointer user_data)
209 {
210   ChildData *child_data = user_data;
211   gint i;
212   gint result;
213
214   /* We're on the child side now.  "Rename" the file descriptors in
215    * child_data.fds[] to stdin/stdout/stderr.
216    *
217    * We don't close the originals.  It's possible that the originals
218    * should not be closed and if they should be closed then they should
219    * have been created O_CLOEXEC.
220    */
221   for (i = 0; i < 3; i++)
222     if (child_data->fds[i] != -1 && child_data->fds[i] != i)
223       {
224         do
225           result = dup2 (child_data->fds[i], i);
226         while (result == -1 && errno == EINTR);
227       }
228
229   /* Basic fd assignments we can just unset FD_CLOEXEC */
230   if (child_data->basic_fd_assignments)
231     {
232       for (i = 0; i < child_data->basic_fd_assignments->len; i++)
233         {
234           gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
235
236           unset_cloexec (fd);
237         }
238     }
239
240   /* If we're doing remapping fd assignments, we need to handle
241    * the case where the user has specified e.g.:
242    * 5 -> 4, 4 -> 6
243    *
244    * We do this by duping the source fds temporarily.
245    */ 
246   if (child_data->needdup_fd_assignments)
247     {
248       for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
249         {
250           gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
251           gint new_parent_fd;
252
253           do
254             new_parent_fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
255           while (parent_fd == -1 && errno == EINTR);
256
257           g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
258         }
259       for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
260         {
261           gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
262           gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
263
264           if (parent_fd == child_fd)
265             {
266               unset_cloexec (parent_fd);
267             }
268           else
269             {
270               do
271                 result = dup2 (parent_fd, child_fd);
272               while (result == -1 && errno == EINTR);
273               (void) close (parent_fd);
274             }
275         }
276     }
277
278   if (child_data->child_setup_func)
279     child_data->child_setup_func (child_data->child_setup_data);
280 }
281
282 static GInputStream *
283 platform_input_stream_from_spawn_fd (gint fd)
284 {
285   if (fd < 0)
286     return NULL;
287
288 #ifdef G_OS_UNIX
289   return g_unix_input_stream_new (fd, TRUE);
290 #else
291   return g_win32_input_stream_new_from_fd (fd, TRUE);
292 #endif
293 }
294
295 static GOutputStream *
296 platform_output_stream_from_spawn_fd (gint fd)
297 {
298   if (fd < 0)
299     return NULL;
300
301 #ifdef G_OS_UNIX
302   return g_unix_output_stream_new (fd, TRUE);
303 #else
304   return g_win32_output_stream_new_from_fd (fd, TRUE);
305 #endif
306 }
307
308 #ifdef G_OS_UNIX
309 static gint
310 unix_open_file (const char  *filename,
311                 gint         mode,
312                 GError     **error)
313 {
314   gint my_fd;
315
316   my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
317
318   /* If we return -1 we should also set the error */
319   if (my_fd < 0)
320     {
321       gint saved_errno = errno;
322       char *display_name;
323
324       display_name = g_filename_display_name (filename);
325       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
326                    _("Error opening file '%s': %s"), display_name,
327                    g_strerror (saved_errno));
328       g_free (display_name);
329       /* fall through... */
330     }
331
332   return my_fd;
333 }
334 #endif
335
336 static void
337 g_subprocess_set_property (GObject      *object,
338                            guint         prop_id,
339                            const GValue *value,
340                            GParamSpec   *pspec)
341 {
342   GSubprocess *self = G_SUBPROCESS (object);
343
344   switch (prop_id)
345     {
346     case PROP_FLAGS:
347       self->flags = g_value_get_flags (value);
348       break;
349
350     case PROP_ARGV:
351       self->argv = g_value_dup_boxed (value);
352       break;
353
354     default:
355       g_assert_not_reached ();
356     }
357 }
358
359 static gboolean
360 g_subprocess_exited (GPid     pid,
361                      gint     status,
362                      gpointer user_data)
363 {
364   GSubprocess *self = user_data;
365   GSList *tasks;
366
367   g_assert (self->pid == pid);
368
369   g_mutex_lock (&self->pending_waits_lock);
370   self->status = status;
371   tasks = self->pending_waits;
372   self->pending_waits = NULL;
373   self->pid = 0;
374   g_mutex_unlock (&self->pending_waits_lock);
375
376   /* Signal anyone in g_subprocess_wait_async() to wake up now */
377   while (tasks)
378     {
379       g_task_return_boolean (tasks->data, TRUE);
380       tasks = g_slist_delete_link (tasks, tasks);
381     }
382
383   g_spawn_close_pid (pid);
384
385   return FALSE;
386 }
387
388 static gboolean
389 initable_init (GInitable     *initable,
390                GCancellable  *cancellable,
391                GError       **error)
392 {
393   GSubprocess *self = G_SUBPROCESS (initable);
394   ChildData child_data = { { -1, -1, -1 }, 0 };
395   gint *pipe_ptrs[3] = { NULL, NULL, NULL };
396   gint pipe_fds[3] = { -1, -1, -1 };
397   gint close_fds[3] = { -1, -1, -1 };
398   GSpawnFlags spawn_flags = 0;
399   gboolean success = FALSE;
400   gint i;
401
402   /* this is a programmer error */
403   if (!self->argv || !self->argv[0] || !self->argv[0][0])
404     return FALSE;
405
406   if (g_cancellable_set_error_if_cancelled (cancellable, error))
407     return FALSE;
408
409   /* We must setup the three fds that will end up in the child as stdin,
410    * stdout and stderr.
411    *
412    * First, stdin.
413    */
414   if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
415     spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
416   else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
417     pipe_ptrs[0] = &pipe_fds[0];
418 #ifdef G_OS_UNIX
419   else if (self->launcher)
420     {
421       if (self->launcher->stdin_fd != -1)
422         child_data.fds[0] = self->launcher->stdin_fd;
423       else if (self->launcher->stdin_path != NULL)
424         {
425           child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
426           if (child_data.fds[0] == -1)
427             goto out;
428         }
429     }
430 #endif
431
432   /* Next, stdout. */
433   if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
434     spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
435   else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
436     pipe_ptrs[1] = &pipe_fds[1];
437 #ifdef G_OS_UNIX
438   else if (self->launcher)
439     {
440       if (self->launcher->stdout_fd != -1)
441         child_data.fds[1] = self->launcher->stdout_fd;
442       else if (self->launcher->stdout_path != NULL)
443         {
444           child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
445           if (child_data.fds[1] == -1)
446             goto out;
447         }
448     }
449 #endif
450
451   /* Finally, stderr. */
452   if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
453     spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
454   else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
455     pipe_ptrs[2] = &pipe_fds[2];
456   else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
457     /* This will work because stderr gets setup after stdout. */
458     child_data.fds[2] = 1;
459 #ifdef G_OS_UNIX
460   else if (self->launcher)
461     {
462       if (self->launcher->stderr_fd != -1)
463         child_data.fds[2] = self->launcher->stderr_fd;
464       else if (self->launcher->stderr_path != NULL)
465         {
466           child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
467           if (child_data.fds[2] == -1)
468             goto out;
469         }
470     }
471 #endif
472
473 #ifdef G_OS_UNIX
474   if (self->launcher)
475     {
476       child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
477       child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
478     }
479 #endif
480
481   /* argv0 has no '/' in it?  We better do a PATH lookup. */
482   if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
483     {
484       if (self->launcher && self->launcher->path_from_envp)
485         spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
486       else
487         spawn_flags |= G_SPAWN_SEARCH_PATH;
488     }
489
490   if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
491     spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
492
493   spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
494   spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
495
496   child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
497   child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
498   success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
499                                       self->argv,
500                                       self->launcher ? self->launcher->envp : NULL,
501                                       spawn_flags,
502                                       child_setup, &child_data,
503                                       &self->pid,
504                                       pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
505                                       error);
506   g_assert (success == (self->pid != 0));
507
508   {
509     guint64 identifier;
510     gint s;
511
512 #ifdef G_OS_WIN32
513     identifier = (guint64) GetProcessId (self->pid);
514 #else
515     identifier = (guint64) self->pid;
516 #endif
517
518     s = snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
519     g_assert (0 < s && s < sizeof self->identifier);
520   }
521
522   /* Start attempting to reap the child immediately */
523   if (success)
524     {
525       GMainContext *worker_context;
526       GSource *source;
527
528       worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
529       source = g_child_watch_source_new (self->pid);
530       g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
531       g_source_attach (source, worker_context);
532       g_source_unref (source);
533     }
534
535 out:
536   /* we don't need this past init... */
537   self->launcher = NULL;
538
539   for (i = 0; i < 3; i++)
540     if (close_fds[i] != -1)
541       close (close_fds[i]);
542
543   self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
544   self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
545   self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
546
547   return success;
548 }
549
550 static void
551 g_subprocess_finalize (GObject *object)
552 {
553   GSubprocess *self = G_SUBPROCESS (object);
554
555   g_assert (self->pending_waits == NULL);
556   g_assert (self->pid == 0);
557
558   g_clear_object (&self->stdin_pipe);
559   g_clear_object (&self->stdout_pipe);
560   g_clear_object (&self->stderr_pipe);
561   g_free (self->argv);
562
563   G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
564 }
565
566 static void
567 g_subprocess_init (GSubprocess  *self)
568 {
569 }
570
571 static void
572 initable_iface_init (GInitableIface *initable_iface)
573 {
574   initable_iface->init = initable_init;
575 }
576
577 static void
578 g_subprocess_class_init (GSubprocessClass *class)
579 {
580   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
581
582   gobject_class->finalize = g_subprocess_finalize;
583   gobject_class->set_property = g_subprocess_set_property;
584
585   g_object_class_install_property (gobject_class, PROP_FLAGS,
586                                    g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
587                                                        G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
588                                                        G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
589   g_object_class_install_property (gobject_class, PROP_ARGV,
590                                    g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
591                                                        G_TYPE_STRV, G_PARAM_WRITABLE |
592                                                        G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
593 }
594
595 /**
596  * g_subprocess_new: (skip)
597  *
598  * Create a new process with the given flags and varargs argument list.
599  *
600  * The argument list must be terminated with %NULL.
601  *
602  * Returns: A newly created #GSubprocess, or %NULL on error (and @error
603  *   will be set)
604  *
605  * Since: 2.40
606  */
607 GSubprocess *
608 g_subprocess_new (GSubprocessFlags   flags,
609                   GError           **error,
610                   const gchar       *argv0,
611                   ...)
612 {
613   GSubprocess *result;
614   GPtrArray *args;
615   const gchar *arg;
616   va_list ap;
617
618   g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
619   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
620
621   args = g_ptr_array_new ();
622
623   va_start (ap, argv0);
624   g_ptr_array_add (args, (gchar *) argv0);
625   while ((arg = va_arg (ap, const gchar *)))
626     g_ptr_array_add (args, (gchar *) arg);
627   g_ptr_array_add (args, NULL);
628
629   result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
630
631   g_ptr_array_free (args, TRUE);
632
633   return result;
634 }
635
636 /**
637  * g_subprocess_newv:
638  *
639  * Create a new process with the given flags and argument list.
640  *
641  * The argument list is expected to be %NULL-terminated.
642  *
643  * Returns: A newly created #GSubprocess, or %NULL on error (and @error
644  *   will be set)
645  *
646  * Since: 2.40
647  * Rename to: g_subprocess_new
648  */
649 GSubprocess *
650 g_subprocess_newv (const gchar * const  *argv,
651                    GSubprocessFlags      flags,
652                    GError              **error)
653 {
654   g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
655
656   return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
657                          "argv", argv,
658                          "flags", flags,
659                          NULL);
660 }
661
662 const gchar *
663 g_subprocess_get_identifier (GSubprocess *subprocess)
664 {
665   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
666
667   if (subprocess->pid)
668     return subprocess->identifier;
669   else
670     return NULL;
671 }
672
673 /**
674  * g_subprocess_get_stdin_pipe:
675  * @subprocess: a #GSubprocess
676  *
677  * Gets the #GOutputStream that you can write to in order to give data
678  * to the stdin of @subprocess.
679  *
680  * The process must have been created with
681  * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
682  *
683  * Returns: the stdout pipe
684  *
685  * Since: 2.40
686  **/
687 GOutputStream *
688 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
689 {
690   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
691   g_return_val_if_fail (subprocess->stdin_pipe, NULL);
692
693   return subprocess->stdin_pipe;
694 }
695
696 /**
697  * g_subprocess_get_stdout_pipe:
698  * @subprocess: a #GSubprocess
699  *
700  * Gets the #GInputStream from which to read the stdout output of
701  * @subprocess.
702  *
703  * The process must have been created with
704  * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
705  *
706  * Returns: the stdout pipe
707  *
708  * Since: 2.40
709  **/
710 GInputStream *
711 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
712 {
713   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
714   g_return_val_if_fail (subprocess->stdout_pipe, NULL);
715
716   return subprocess->stdout_pipe;
717 }
718
719 /**
720  * g_subprocess_get_stderr_pipe:
721  * @subprocess: a #GSubprocess
722  *
723  * Gets the #GInputStream from which to read the stderr output of
724  * @subprocess.
725  *
726  * The process must have been created with
727  * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
728  *
729  * Returns: the stderr pipe
730  *
731  * Since: 2.40
732  **/
733 GInputStream *
734 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
735 {
736   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
737   g_return_val_if_fail (subprocess->stderr_pipe, NULL);
738
739   return subprocess->stderr_pipe;
740 }
741
742 static void
743 g_subprocess_wait_cancelled (GCancellable *cancellable,
744                              gpointer      user_data)
745 {
746   GTask *task = user_data;
747   GSubprocess *self;
748
749   self = g_task_get_source_object (task);
750
751   g_mutex_lock (&self->pending_waits_lock);
752   self->pending_waits = g_slist_remove (self->pending_waits, task);
753   g_mutex_unlock (&self->pending_waits_lock);
754
755   g_task_return_boolean (task, FALSE);
756   g_object_unref (task);
757 }
758
759 /**
760  * g_subprocess_wait_async:
761  * @subprocess: a #GSubprocess
762  * @cancellable: a #GCancellable, or %NULL
763  * @callback: a #GAsyncReadyCallback to call when the operation is complete
764  * @user_data: user_data for @callback
765  *
766  * Wait for the subprocess to terminate.
767  *
768  * This is the asynchronous version of g_subprocess_wait().
769  *
770  * Since: 2.40
771  */
772 void
773 g_subprocess_wait_async (GSubprocess         *subprocess,
774                          GCancellable        *cancellable,
775                          GAsyncReadyCallback  callback,
776                          gpointer             user_data)
777 {
778   GTask *task;
779
780   task = g_task_new (subprocess, cancellable, callback, user_data);
781
782   g_mutex_lock (&subprocess->pending_waits_lock);
783   if (subprocess->pid)
784     {
785       /* Only bother with cancellable if we're putting it in the list.
786        * If not, it's going to dispatch immediately anyway and we will
787        * see the cancellation in the _finish().
788        */
789       if (cancellable)
790         g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
791
792       subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
793       task = NULL;
794     }
795   g_mutex_unlock (&subprocess->pending_waits_lock);
796
797   /* If we still have task then it's because did_exit is already TRUE */
798   if (task != NULL)
799     {
800       g_task_return_boolean (task, TRUE);
801       g_object_unref (task);
802     }
803 }
804
805 /**
806  * g_subprocess_wait_finish:
807  * @subprocess: a #GSubprocess
808  * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
809  * @error: a pointer to a %NULL #GError, or %NULL
810  *
811  * Collects the result of a previous call to
812  * g_subprocess_wait_async().
813  *
814  * Returns: %TRUE if successful, or %FALSE with @error set
815  *
816  * Since: 2.40
817  */
818 gboolean
819 g_subprocess_wait_finish (GSubprocess   *subprocess,
820                           GAsyncResult  *result,
821                           GError       **error)
822 {
823   return g_task_propagate_boolean (G_TASK (result), error);
824 }
825
826 /* Some generic helpers for emulating synchronous operations using async
827  * operations.
828  */
829 static void
830 g_subprocess_sync_setup (void)
831 {
832   g_main_context_push_thread_default (g_main_context_new ());
833 }
834
835 static void
836 g_subprocess_sync_done (GObject      *source_object,
837                         GAsyncResult *result,
838                         gpointer      user_data)
839 {
840   GAsyncResult **result_ptr = user_data;
841
842   *result_ptr = g_object_ref (result);
843 }
844
845 static void
846 g_subprocess_sync_complete (GAsyncResult **result)
847 {
848   GMainContext *context = g_main_context_get_thread_default ();
849
850   while (!*result)
851     g_main_context_iteration (context, TRUE);
852
853   g_main_context_pop_thread_default (context);
854   g_main_context_unref (context);
855 }
856
857 /**
858  * g_subprocess_wait:
859  * @subprocess: a #GSubprocess
860  * @cancellable: a #GCancellable
861  * @error: a #GError
862  *
863  * Synchronously wait for the subprocess to terminate.
864  *
865  * After the process terminates you can query its exit status with
866  * functions such as g_subprocess_get_if_exited() and
867  * g_subprocess_get_exit_status().
868  *
869  * This function does not fail in the case of the subprocess having
870  * abnormal termination.  See g_subprocess_wait_check() for that.
871  *
872  * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
873  *
874  * Since: 2.40
875  */
876 gboolean
877 g_subprocess_wait (GSubprocess   *subprocess,
878                    GCancellable  *cancellable,
879                    GError       **error)
880 {
881   GAsyncResult *result = NULL;
882   gboolean success;
883
884   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
885
886   /* Synchronous waits are actually the 'more difficult' case because we
887    * need to deal with the possibility of cancellation.  That more or
888    * less implies that we need a main context (to dispatch either of the
889    * possible reasons for the operation ending).
890    *
891    * So we make one and then do this async...
892    */
893
894   if (g_cancellable_set_error_if_cancelled (cancellable, error))
895     return FALSE;
896
897   /* We can shortcut in the case that the process already quit (but only
898    * after we checked the cancellable).
899    */
900   if (subprocess->pid == 0)
901     return TRUE;
902
903   /* Otherwise, we need to do this the long way... */
904   g_subprocess_sync_setup ();
905   g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
906   g_subprocess_sync_complete (&result);
907   success = g_subprocess_wait_finish (subprocess, result, error);
908   g_object_unref (result);
909
910   return success;
911 }
912
913 /**
914  * g_subprocess_wait_check:
915  * @subprocess: a #GSubprocess
916  * @cancellable: a #GCancellable
917  * @error: a #GError
918  *
919  * Combines g_subprocess_wait() with g_spawn_check_exit_status().
920  *
921  * Returns: %TRUE on success, %FALSE if process exited abnormally, or
922  * @cancellable was cancelled
923  *
924  * Since: 2.40
925  */
926 gboolean
927 g_subprocess_wait_check (GSubprocess   *subprocess,
928                          GCancellable  *cancellable,
929                          GError       **error)
930 {
931   return g_subprocess_wait (subprocess, cancellable, error) &&
932          g_spawn_check_exit_status (subprocess->status, error);
933 }
934
935 /**
936  * g_subprocess_wait_check_async:
937  * @subprocess: a #GSubprocess
938  * @cancellable: a #GCancellable, or %NULL
939  * @callback: a #GAsyncReadyCallback to call when the operation is complete
940  * @user_data: user_data for @callback
941  *
942  * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
943  *
944  * This is the asynchronous version of g_subprocess_wait_check().
945  *
946  * Since: 2.40
947  */
948 void
949 g_subprocess_wait_check_async (GSubprocess         *subprocess,
950                                GCancellable        *cancellable,
951                                GAsyncReadyCallback  callback,
952                                gpointer             user_data)
953 {
954   g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
955 }
956
957 /**
958  * g_subprocess_wait_check_finish:
959  * @subprocess: a #GSubprocess
960  * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
961  * @error: a pointer to a %NULL #GError, or %NULL
962  *
963  * Collects the result of a previous call to
964  * g_subprocess_wait_check_async().
965  *
966  * Returns: %TRUE if successful, or %FALSE with @error set
967  *
968  * Since: 2.40
969  */
970 gboolean
971 g_subprocess_wait_check_finish (GSubprocess   *subprocess,
972                                 GAsyncResult  *result,
973                                 GError       **error)
974 {
975   return g_subprocess_wait_finish (subprocess, result, error) &&
976          g_spawn_check_exit_status (subprocess->status, error);
977 }
978
979 #ifdef G_OS_UNIX
980 typedef struct
981 {
982   GSubprocess *subprocess;
983   gint signalnum;
984 } SignalRecord;
985
986 static gboolean
987 g_subprocess_actually_send_signal (gpointer user_data)
988 {
989   SignalRecord *signal_record = user_data;
990
991   /* The pid is set to zero from the worker thread as well, so we don't
992    * need to take a lock in order to prevent it from changing under us.
993    */
994   if (signal_record->subprocess->pid)
995     kill (signal_record->subprocess->pid, signal_record->signalnum);
996
997   g_object_unref (signal_record->subprocess);
998
999   g_slice_free (SignalRecord, signal_record);
1000
1001   return FALSE;
1002 }
1003
1004 static void
1005 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1006                               gint         signalnum)
1007 {
1008   SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1009
1010   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1011
1012   /* This MUST be a lower priority than the priority that the child
1013    * watch source uses in initable_init().
1014    *
1015    * Reaping processes, reporting the results back to GSubprocess and
1016    * sending signals is all done in the glib worker thread.  We cannot
1017    * have a kill() done after the reap and before the report without
1018    * risking killing a process that's no longer there so the kill()
1019    * needs to have the lower priority.
1020    *
1021    * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1022    */
1023   g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1024                               G_PRIORITY_HIGH_IDLE,
1025                               g_subprocess_actually_send_signal,
1026                               g_slice_dup (SignalRecord, &signal_record),
1027                               NULL);
1028 }
1029
1030 /**
1031  * g_subprocess_send_signal:
1032  * @subprocess: a #GSubprocess
1033  * @signal_num: the signal number to send
1034  *
1035  * Sends the UNIX signal @signal_num to the subprocess, if it is still
1036  * running.
1037  *
1038  * This API is race-free.  If the subprocess has terminated, it will not
1039  * be signalled.
1040  *
1041  * This API is not available on Windows.
1042  *
1043  * Since: 2.40
1044  **/
1045 void
1046 g_subprocess_send_signal (GSubprocess *subprocess,
1047                           gint         signal_num)
1048 {
1049   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1050
1051   g_subprocess_dispatch_signal (subprocess, signal_num);
1052 }
1053 #endif
1054
1055 /**
1056  * g_subprocess_force_exit:
1057  * @subprocess: a #GSubprocess
1058  *
1059  * Use an operating-system specific method to attempt an immediate,
1060  * forceful termination of the process.  There is no mechanism to
1061  * determine whether or not the request itself was successful;
1062  * however, you can use g_subprocess_wait() to monitor the status of
1063  * the process after calling this function.
1064  *
1065  * On Unix, this function sends %SIGKILL.
1066  *
1067  * Since: 2.40
1068  **/
1069 void
1070 g_subprocess_force_exit (GSubprocess *subprocess)
1071 {
1072   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1073
1074 #ifdef G_OS_UNIX
1075   g_subprocess_dispatch_signal (subprocess, SIGKILL);
1076 #else
1077   TerminateProcess (subprocess->pid, 1);
1078 #endif
1079 }
1080
1081 /**
1082  * g_subprocess_get_status:
1083  * @subprocess: a #GSubprocess
1084  *
1085  * Gets the raw status code of the process, as from waitpid().
1086  *
1087  * This value has no particular meaning, but it can be used with the
1088  * macros defined by the system headers such as WIFEXITED.  It can also
1089  * be used with g_spawn_check_exit_status().
1090  *
1091  * It is more likely that you want to use g_subprocess_get_if_exited()
1092  * followed by g_subprocess_get_exit_status().
1093  *
1094  * It is an error to call this function before g_subprocess_wait() has
1095  * returned.
1096  *
1097  * Returns: the (meaningless) waitpid() exit status from the kernel
1098  *
1099  * Since: 2.40
1100  **/
1101 gint
1102 g_subprocess_get_status (GSubprocess *subprocess)
1103 {
1104   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1105   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1106
1107   return subprocess->status;
1108 }
1109
1110 /**
1111  * g_subprocess_get_successful:
1112  * @subprocess: a #GSubprocess
1113  *
1114  * Checks if the process was "successful".  A process is considered
1115  * successful if it exited cleanly with an exit status of 0, either by
1116  * way of the exit() system call or return from main().
1117  *
1118  * It is an error to call this function before g_subprocess_wait() has
1119  * returned.
1120  *
1121  * Returns: %TRUE if the process exited cleanly with a exit status of 0
1122  *
1123  * Since: 2.40
1124  **/
1125 gboolean
1126 g_subprocess_get_successful (GSubprocess *subprocess)
1127 {
1128   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1129   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1130
1131   return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1132 }
1133
1134 /**
1135  * g_subprocess_get_if_exited:
1136  * @subprocess: a #GSubprocess
1137  *
1138  * Check if the given subprocess exited normally (ie: by way of exit()
1139  * or return from main()).
1140  *
1141  * This is equivalent to the system WIFEXITED macro.
1142  *
1143  * It is an error to call this function before g_subprocess_wait() has
1144  * returned.
1145  *
1146  * Returns: %TRUE if the case of a normal exit
1147  *
1148  * Since: 2.40
1149  **/
1150 gboolean
1151 g_subprocess_get_if_exited (GSubprocess *subprocess)
1152 {
1153   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1154   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1155
1156   return WIFEXITED (subprocess->status);
1157 }
1158
1159 /**
1160  * g_subprocess_get_exit_status:
1161  * @subprocess: a #GSubprocess
1162  *
1163  * Check the exit status of the subprocess, given that it exited
1164  * normally.  This is the value passed to the exit() system call or the
1165  * return value from main.
1166  *
1167  * This is equivalent to the system WEXITSTATUS macro.
1168  *
1169  * It is an error to call this function before g_subprocess_wait() and
1170  * unless g_subprocess_get_if_exited() returned %TRUE.
1171  *
1172  * Returns: the exit status
1173  *
1174  * Since: 2.40
1175  **/
1176 gint
1177 g_subprocess_get_exit_status (GSubprocess *subprocess)
1178 {
1179   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1180   g_return_val_if_fail (subprocess->pid == 0, 1);
1181   g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1182
1183   return WEXITSTATUS (subprocess->status);
1184 }
1185
1186 /**
1187  * g_subprocess_get_if_signaled:
1188  * @subprocess: a #GSubprocess
1189  *
1190  * Check if the given subprocess terminated in response to a signal.
1191  *
1192  * This is equivalent to the system WIFSIGNALED macro.
1193  *
1194  * It is an error to call this function before g_subprocess_wait() has
1195  * returned.
1196  *
1197  * Returns: %TRUE if the case of termination due to a signal
1198  *
1199  * Since: 2.40
1200  **/
1201 gboolean
1202 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1203 {
1204   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1205   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1206
1207   return WIFSIGNALED (subprocess->status);
1208 }
1209
1210 /**
1211  * g_subprocess_get_term_sig:
1212  * @subprocess: a #GSubprocess
1213  *
1214  * Get the signal number that caused the subprocess to terminate, given
1215  * that it terminated due to a signal.
1216  *
1217  * This is equivalent to the system WTERMSIG macro.
1218  *
1219  * It is an error to call this function before g_subprocess_wait() and
1220  * unless g_subprocess_get_if_signaled() returned %TRUE.
1221  *
1222  * Returns: the signal causing termination
1223  *
1224  * Since: 2.40
1225  **/
1226 gint
1227 g_subprocess_get_term_sig (GSubprocess *subprocess)
1228 {
1229   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1230   g_return_val_if_fail (subprocess->pid == 0, 0);
1231   g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1232
1233   return WTERMSIG (subprocess->status);
1234 }
1235
1236 /*< private >*/
1237 void
1238 g_subprocess_set_launcher (GSubprocess         *subprocess,
1239                            GSubprocessLauncher *launcher)
1240 {
1241   subprocess->launcher = launcher;
1242 }
1243
1244
1245 /* g_subprocess_communicate implementation below:
1246  *
1247  * This is a tough problem.  We have to watch 5 things at the same time:
1248  *
1249  *  - writing to stdin made progress
1250  *  - reading from stdout made progress
1251  *  - reading from stderr made progress
1252  *  - process terminated
1253  *  - cancellable being cancelled by caller
1254  *
1255  * We use a GMainContext for all of these (either as async function
1256  * calls or as a GSource (in the case of the cancellable).  That way at
1257  * least we don't have to worry about threading.
1258  *
1259  * For the sync case we use the usual trick of creating a private main
1260  * context and iterating it until completion.
1261  *
1262  * It's very possible that the process will dump a lot of data to stdout
1263  * just before it quits, so we can easily have data to read from stdout
1264  * and see the process has terminated at the same time.  We want to make
1265  * sure that we read all of the data from the pipes first, though, so we
1266  * do IO operations at a higher priority than the wait operation (which
1267  * is at G_IO_PRIORITY_DEFAULT).  Even in the case that we have to do
1268  * multiple reads to get this data, the pipe() will always be polling
1269  * as ready and with the async result for the read at a higher priority,
1270  * the main context will not dispatch the completion for the wait().
1271  *
1272  * We keep our own private GCancellable.  In the event that any of the
1273  * above suffers from an error condition (including the user cancelling
1274  * their cancellable) we immediately dispatch the GTask with the error
1275  * result and fire our cancellable to cleanup any pending operations.
1276  * In the case that the error is that the user's cancellable was fired,
1277  * it's vaguely wasteful to report an error because GTask will handle
1278  * this automatically, so we just return FALSE.
1279  *
1280  * We let each pending sub-operation take a ref on the GTask of the
1281  * communicate operation.  We have to be careful that we don't report
1282  * the task completion more than once, though, so we keep a flag for
1283  * that.
1284  */
1285 typedef struct
1286 {
1287   const gchar *stdin_data;
1288   gsize stdin_length;
1289   gsize stdin_offset;
1290
1291   gboolean add_nul;
1292
1293   GInputStream *stdin_buf;
1294   GMemoryOutputStream *stdout_buf;
1295   GMemoryOutputStream *stderr_buf;
1296
1297   GCancellable *cancellable;
1298   GSource      *cancellable_source;
1299
1300   guint         outstanding_ops;
1301   gboolean      reported_error;
1302 } CommunicateState;
1303
1304 static void
1305 g_subprocess_communicate_made_progress (GObject      *source_object,
1306                                         GAsyncResult *result,
1307                                         gpointer      user_data)
1308 {
1309   CommunicateState *state;
1310   GSubprocess *subprocess;
1311   GError *error = NULL;
1312   gpointer source;
1313   GTask *task;
1314
1315   g_assert (source_object != NULL);
1316
1317   task = user_data;
1318   subprocess = g_task_get_source_object (task);
1319   state = g_task_get_task_data (task);
1320   source = source_object;
1321
1322   state->outstanding_ops--;
1323
1324   if (source == subprocess->stdin_pipe ||
1325       source == state->stdout_buf ||
1326       source == state->stderr_buf)
1327     {
1328       if (!g_output_stream_splice_finish ((GOutputStream*)source, result, &error))
1329         goto out;
1330
1331       if (source == state->stdout_buf ||
1332           source == state->stderr_buf)
1333         {
1334           /* This is a memory stream, so it can't be cancelled or return
1335            * an error really.
1336            */
1337           if (state->add_nul)
1338             {
1339               gsize bytes_written;
1340               if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1341                                               NULL, &error))
1342                 goto out;
1343             }
1344           if (!g_output_stream_close (source, NULL, &error))
1345             goto out;
1346         }
1347     }
1348   else if (source == subprocess)
1349     {
1350       (void) g_subprocess_wait_finish (subprocess, result, &error);
1351     }
1352   else
1353     g_assert_not_reached ();
1354
1355  out:
1356   if (error)
1357     {
1358       /* Only report the first error we see.
1359        *
1360        * We might be seeing an error as a result of the cancellation
1361        * done when the process quits.
1362        */
1363       if (!state->reported_error)
1364         {
1365           state->reported_error = TRUE;
1366           g_cancellable_cancel (state->cancellable);
1367           g_task_return_error (task, error);
1368         }
1369       else
1370         g_error_free (error);
1371     }
1372   else if (state->outstanding_ops == 0)
1373     {
1374       g_task_return_boolean (task, TRUE);
1375     }
1376
1377   /* And drop the original ref */
1378   g_object_unref (task);
1379 }
1380
1381 static gboolean
1382 g_subprocess_communicate_cancelled (gpointer user_data)
1383 {
1384   CommunicateState *state = user_data;
1385
1386   g_cancellable_cancel (state->cancellable);
1387
1388   return FALSE;
1389 }
1390
1391 static void
1392 g_subprocess_communicate_state_free (gpointer data)
1393 {
1394   CommunicateState *state = data;
1395
1396   g_clear_object (&state->stdin_buf);
1397   g_clear_object (&state->stdout_buf);
1398   g_clear_object (&state->stderr_buf);
1399
1400   if (!g_source_is_destroyed (state->cancellable_source))
1401     g_source_destroy (state->cancellable_source);
1402   g_source_unref (state->cancellable_source);
1403
1404   g_slice_free (CommunicateState, state);
1405 }
1406
1407 static CommunicateState *
1408 g_subprocess_communicate_internal (GSubprocess         *subprocess,
1409                                    gboolean             add_nul,
1410                                    GBytes              *stdin_buf,
1411                                    GCancellable        *cancellable,
1412                                    GAsyncReadyCallback  callback,
1413                                    gpointer             user_data)
1414 {
1415   CommunicateState *state;
1416   GTask *task;
1417
1418   task = g_task_new (subprocess, cancellable, callback, user_data);
1419   state = g_slice_new0 (CommunicateState);
1420   g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1421
1422   state->cancellable = g_cancellable_new ();
1423   state->add_nul = add_nul;
1424
1425   if (cancellable)
1426     {
1427       state->cancellable_source = g_cancellable_source_new (cancellable);
1428       /* No ref held here, but we unref the source from state's free function */
1429       g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1430       g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1431     }
1432
1433   if (subprocess->stdin_pipe)
1434     {
1435       g_assert (stdin_buf != NULL);
1436       state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1437       g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1438                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1439                                     G_PRIORITY_DEFAULT, state->cancellable,
1440                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1441       state->outstanding_ops++;
1442     }
1443
1444   if (subprocess->stdout_pipe)
1445     {
1446       state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1447       g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1448                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1449                                     G_PRIORITY_DEFAULT, state->cancellable,
1450                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1451       state->outstanding_ops++;
1452     }
1453
1454   if (subprocess->stderr_pipe)
1455     {
1456       state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1457       g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1458                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1459                                     G_PRIORITY_DEFAULT, state->cancellable,
1460                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1461       state->outstanding_ops++;
1462     }
1463
1464   g_subprocess_wait_async (subprocess, state->cancellable,
1465                            g_subprocess_communicate_made_progress, g_object_ref (task));
1466   state->outstanding_ops++;
1467
1468   return state;
1469 }
1470
1471 /**
1472  * g_subprocess_communicate:
1473  * @subprocess: a #GSubprocess
1474  * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1475  * @cancellable: a #GCancellable
1476  * @stdout_buf: (out): data read from the subprocess stdout
1477  * @stderr_buf: (out): data read from the subprocess stderr
1478  * @error: a pointer to a %NULL #GError pointer, or %NULL
1479  *
1480  * Communicate with the subprocess until it terminates, and all input
1481  * and output has been completed.
1482  *
1483  * If @stdin is given, the subprocess must have been created with
1484  * %G_SUBPROCESS_FLAGS_STDIN_PIPE.  The given data is fed to the
1485  * stdin of the subprocess and the pipe is closed (ie: EOF).
1486  *
1487  * At the same time (as not to cause blocking when dealing with large
1488  * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1489  * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1490  * streams.  The data that was read is returned in @stdout and/or
1491  * the @stderr.
1492  *
1493  * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1494  * @stdout_buf will contain the data read from stdout.  Otherwise, for
1495  * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1496  * @stdout_buf will be set to %NULL.  Similar provisions apply to
1497  * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1498  *
1499  * As usual, any output variable may be given as %NULL to ignore it.
1500  *
1501  * If you desire the stdout and stderr data to be interleaved, create
1502  * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1503  * %G_SUBPROCESS_FLAGS_STDERR_MERGE.  The merged result will be returned
1504  * in @stdout_buf and @stderr_buf will be set to %NULL.
1505  *
1506  * In case of any error (including cancellation), %FALSE will be
1507  * returned with @error set.  Some or all of the stdin data may have
1508  * been written.  Any stdout or stderr data that has been read will be
1509  * discarded. None of the out variables (aside from @error) will have
1510  * been set to anything in particular and should not be inspected.
1511  *
1512  * In the case that %TRUE is returned, the subprocess has exited and the
1513  * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1514  * g_subprocess_get_exit_status()) may be used.
1515  *
1516  * You should not attempt to use any of the subprocess pipes after
1517  * starting this function, since they may be left in strange states,
1518  * even if the operation was cancelled.  You should especially not
1519  * attempt to interact with the pipes while the operation is in progress
1520  * (either from another thread or if using the asynchronous version).
1521  *
1522  * Returns: %TRUE if successful
1523  *
1524  * Since: 2.40
1525  **/
1526 gboolean
1527 g_subprocess_communicate (GSubprocess   *subprocess,
1528                           GBytes        *stdin_buf,
1529                           GCancellable  *cancellable,
1530                           GBytes       **stdout_buf,
1531                           GBytes       **stderr_buf,
1532                           GError       **error)
1533 {
1534   GAsyncResult *result = NULL;
1535   gboolean success;
1536
1537   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1538   g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1539   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1540   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1541
1542   g_subprocess_sync_setup ();
1543   g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1544                                      g_subprocess_sync_done, &result);
1545   g_subprocess_sync_complete (&result);
1546   success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1547   g_object_unref (result);
1548
1549   return success;
1550 }
1551
1552 /**
1553  * g_subprocess_communicate_async:
1554  * @subprocess: Self
1555  * @stdin_buf: Input data
1556  * @cancellable: Cancellable
1557  * @callback: Callback
1558  * @user_data: User data
1559  *
1560  * Asynchronous version of g_subprocess_communicate().  Complete
1561  * invocation with g_subprocess_communicate_finish().
1562  */
1563 void
1564 g_subprocess_communicate_async (GSubprocess         *subprocess,
1565                                 GBytes              *stdin_buf,
1566                                 GCancellable        *cancellable,
1567                                 GAsyncReadyCallback  callback,
1568                                 gpointer             user_data)
1569 {
1570   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1571   g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1572   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1573
1574   g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1575 }
1576
1577 /**
1578  * g_subprocess_communicate_finish:
1579  * @subprocess: Self
1580  * @result: Result
1581  * @stdout_buf: (out): Return location for stdout data
1582  * @stderr_buf: (out): Return location for stderr data
1583  * @error: Error
1584  *
1585  * Complete an invocation of g_subprocess_communicate_async().
1586  */
1587 gboolean
1588 g_subprocess_communicate_finish (GSubprocess   *subprocess,
1589                                  GAsyncResult  *result,
1590                                  GBytes       **stdout_buf,
1591                                  GBytes       **stderr_buf,
1592                                  GError       **error)
1593 {
1594   gboolean success;
1595   CommunicateState *state;
1596
1597   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1598   g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1599   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1600
1601   g_object_ref (result);
1602
1603   state = g_task_get_task_data ((GTask*)result);
1604   success = g_task_propagate_boolean ((GTask*)result, error);
1605
1606   if (success)
1607     {
1608       if (stdout_buf)
1609         *stdout_buf = g_memory_output_stream_steal_as_bytes (state->stdout_buf);
1610       if (stderr_buf)
1611         *stderr_buf = g_memory_output_stream_steal_as_bytes (state->stderr_buf);
1612     }
1613
1614   g_object_unref (result);
1615   return success;
1616 }
1617
1618 /**
1619  * g_subprocess_communicate_utf8:
1620  * @subprocess: a #GSubprocess
1621  * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1622  * @cancellable: a #GCancellable
1623  * @stdout_buf: (out): data read from the subprocess stdout
1624  * @stderr_buf: (out): data read from the subprocess stderr
1625  * @error: a pointer to a %NULL #GError pointer, or %NULL
1626  *
1627  * Like g_subprocess_communicate(), but validates the output of the
1628  * process as UTF-8, and returns it as a regular NUL terminated string.
1629  */
1630 gboolean
1631 g_subprocess_communicate_utf8 (GSubprocess   *subprocess,
1632                                const char    *stdin_buf,
1633                                GCancellable  *cancellable,
1634                                char         **stdout_buf,
1635                                char         **stderr_buf,
1636                                GError       **error)
1637 {
1638   GAsyncResult *result = NULL;
1639   gboolean success;
1640   GBytes *stdin_bytes;
1641
1642   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1643   g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1644   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1645   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1646
1647   stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1648
1649   g_subprocess_sync_setup ();
1650   g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1651                                      g_subprocess_sync_done, &result);
1652   g_subprocess_sync_complete (&result);
1653   success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1654   g_object_unref (result);
1655
1656   g_bytes_unref (stdin_bytes);
1657   return success;
1658 }
1659
1660 /**
1661  * g_subprocess_communicate_utf8_async:
1662  * @subprocess: Self
1663  * @stdin_buf: Input data
1664  * @cancellable: Cancellable
1665  * @callback: Callback
1666  * @user_data: User data
1667  *
1668  * Asynchronous version of g_subprocess_communicate_utf().  Complete
1669  * invocation with g_subprocess_communicate_utf8_finish().
1670  */
1671 void
1672 g_subprocess_communicate_utf8_async (GSubprocess         *subprocess,
1673                                      const char          *stdin_buf,
1674                                      GCancellable        *cancellable,
1675                                      GAsyncReadyCallback  callback,
1676                                      gpointer             user_data)
1677 {
1678   GBytes *stdin_bytes;
1679
1680   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1681   g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1682   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1683
1684   stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1685   g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1686   g_bytes_unref (stdin_bytes);
1687 }
1688
1689 static gboolean
1690 communicate_result_validate_utf8 (const char            *stream_name,
1691                                   char                 **return_location,
1692                                   GMemoryOutputStream   *buffer,
1693                                   GError               **error)
1694 {
1695   if (return_location == NULL)
1696     return TRUE;
1697
1698   if (buffer)
1699     {
1700       const char *end;
1701       *return_location = g_memory_output_stream_steal_data (buffer);
1702       if (!g_utf8_validate (*return_location, -1, &end))
1703         {
1704           g_free (*return_location);
1705           g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1706                        "Invalid UTF-8 in child %s at offset %lu",
1707                        stream_name,
1708                        (unsigned long) (end - *return_location));
1709           return FALSE;
1710         }
1711     }
1712   else
1713     *return_location = NULL;
1714
1715   return TRUE;
1716 }
1717
1718 /**
1719  * g_subprocess_communicate_utf8_finish:
1720  * @subprocess: Self
1721  * @result: Result
1722  * @stdout_buf: (out): Return location for stdout data
1723  * @stderr_buf: (out): Return location for stderr data
1724  * @error: Error
1725  *
1726  * Complete an invocation of g_subprocess_communicate_utf8_async().
1727  */
1728 gboolean
1729 g_subprocess_communicate_utf8_finish (GSubprocess   *subprocess,
1730                                       GAsyncResult  *result,
1731                                       char         **stdout_buf,
1732                                       char         **stderr_buf,
1733                                       GError       **error)
1734 {
1735   gboolean ret = FALSE;
1736   CommunicateState *state;
1737
1738   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1739   g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1740   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1741
1742   g_object_ref (result);
1743
1744   state = g_task_get_task_data ((GTask*)result);
1745   if (!g_task_propagate_boolean ((GTask*)result, error))
1746     goto out;
1747
1748   /* TODO - validate UTF-8 while streaming, rather than all at once.
1749    */
1750   if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1751                                          state->stdout_buf,
1752                                          error))
1753     goto out;
1754   if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1755                                          state->stderr_buf,
1756                                          error))
1757     goto out;
1758
1759   ret = TRUE;
1760  out:
1761   g_object_unref (result);
1762   return ret;
1763 }