Blame gio/gsubprocess.c

Packit ae235b
/* GIO - GLib Input, Output and Streaming Library
Packit ae235b
 *
Packit ae235b
 * Copyright © 2012, 2013 Red Hat, Inc.
Packit ae235b
 * Copyright © 2012, 2013 Canonical Limited
Packit ae235b
 *
Packit ae235b
 * This library is free software; you can redistribute it and/or
Packit ae235b
 * modify it under the terms of the GNU Lesser General Public
Packit ae235b
 * License as published by the Free Software Foundation; either
Packit ae235b
 * version 2.1 of the License, or (at your option) any later version.
Packit ae235b
 *
Packit ae235b
 * See the included COPYING file for more information.
Packit ae235b
 *
Packit ae235b
 * Authors: Colin Walters <walters@verbum.org>
Packit ae235b
 *          Ryan Lortie <desrt@desrt.ca>
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * SECTION:gsubprocess
Packit ae235b
 * @title: GSubprocess
Packit ae235b
 * @short_description: Child processes
Packit ae235b
 * @include: gio/gio.h
Packit ae235b
 * @see_also: #GSubprocessLauncher
Packit ae235b
 *
Packit ae235b
 * #GSubprocess allows the creation of and interaction with child
Packit ae235b
 * processes.
Packit ae235b
 *
Packit ae235b
 * Processes can be communicated with using standard GIO-style APIs (ie:
Packit ae235b
 * #GInputStream, #GOutputStream).  There are GIO-style APIs to wait for
Packit ae235b
 * process termination (ie: cancellable and with an asynchronous
Packit ae235b
 * variant).
Packit ae235b
 *
Packit ae235b
 * There is an API to force a process to terminate, as well as a
Packit ae235b
 * race-free API for sending UNIX signals to a subprocess.
Packit ae235b
 *
Packit ae235b
 * One major advantage that GIO brings over the core GLib library is
Packit ae235b
 * comprehensive API for asynchronous I/O, such
Packit ae235b
 * g_output_stream_splice_async().  This makes GSubprocess
Packit ae235b
 * significantly more powerful and flexible than equivalent APIs in
Packit ae235b
 * some other languages such as the `subprocess.py`
Packit ae235b
 * included with Python.  For example, using #GSubprocess one could
Packit ae235b
 * create two child processes, reading standard output from the first,
Packit ae235b
 * processing it, and writing to the input stream of the second, all
Packit ae235b
 * without blocking the main loop.
Packit ae235b
 *
Packit ae235b
 * A powerful g_subprocess_communicate() API is provided similar to the
Packit ae235b
 * `communicate()` method of `subprocess.py`. This enables very easy
Packit ae235b
 * interaction with a subprocess that has been opened with pipes.
Packit ae235b
 *
Packit ae235b
 * #GSubprocess defaults to tight control over the file descriptors open
Packit ae235b
 * in the child process, avoiding dangling-fd issues that are caused by
Packit ae235b
 * a simple fork()/exec().  The only open file descriptors in the
Packit ae235b
 * spawned process are ones that were explicitly specified by the
Packit ae235b
 * #GSubprocess API (unless %G_SUBPROCESS_FLAGS_INHERIT_FDS was
Packit ae235b
 * specified).
Packit ae235b
 *
Packit ae235b
 * #GSubprocess will quickly reap all child processes as they exit,
Packit ae235b
 * avoiding "zombie processes" remaining around for long periods of
Packit ae235b
 * time.  g_subprocess_wait() can be used to wait for this to happen,
Packit ae235b
 * but it will happen even without the call being explicitly made.
Packit ae235b
 *
Packit ae235b
 * As a matter of principle, #GSubprocess has no API that accepts
Packit ae235b
 * shell-style space-separated strings.  It will, however, match the
Packit ae235b
 * typical shell behaviour of searching the PATH for executables that do
Packit ae235b
 * not contain a directory separator in their name.
Packit ae235b
 *
Packit ae235b
 * #GSubprocess attempts to have a very simple API for most uses (ie:
Packit ae235b
 * spawning a subprocess with arguments and support for most typical
Packit ae235b
 * kinds of input and output redirection).  See g_subprocess_new(). The
Packit ae235b
 * #GSubprocessLauncher API is provided for more complicated cases
Packit ae235b
 * (advanced types of redirection, environment variable manipulation,
Packit ae235b
 * change of working directory, child setup functions, etc).
Packit ae235b
 *
Packit ae235b
 * A typical use of #GSubprocess will involve calling
Packit ae235b
 * g_subprocess_new(), followed by g_subprocess_wait_async() or
Packit ae235b
 * g_subprocess_wait().  After the process exits, the status can be
Packit ae235b
 * checked using functions such as g_subprocess_get_if_exited() (which
Packit ae235b
 * are similar to the familiar WIFEXITED-style POSIX macros).
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
Packit ae235b
#include "config.h"
Packit ae235b
Packit ae235b
#include "gsubprocess.h"
Packit ae235b
#include "gsubprocesslauncher-private.h"
Packit ae235b
#include "gasyncresult.h"
Packit ae235b
#include "giostream.h"
Packit ae235b
#include "gmemoryinputstream.h"
Packit ae235b
#include "glibintl.h"
Packit ae235b
#include "glib-private.h"
Packit ae235b
Packit ae235b
#include <string.h>
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
#include <gio/gunixoutputstream.h>
Packit ae235b
#include <gio/gfiledescriptorbased.h>
Packit ae235b
#include <gio/gunixinputstream.h>
Packit ae235b
#include <gstdio.h>
Packit ae235b
#include <glib-unix.h>
Packit ae235b
#include <fcntl.h>
Packit ae235b
#endif
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
#include <windows.h>
Packit ae235b
#include <io.h>
Packit ae235b
#include "giowin32-priv.h"
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#ifndef O_BINARY
Packit ae235b
#define O_BINARY 0
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#ifndef O_CLOEXEC
Packit ae235b
#define O_CLOEXEC 0
Packit ae235b
#else
Packit ae235b
#define HAVE_O_CLOEXEC 1
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#define COMMUNICATE_READ_SIZE 4096
Packit ae235b
Packit ae235b
/* A GSubprocess can have two possible states: running and not.
Packit ae235b
 *
Packit ae235b
 * These two states are reflected by the value of 'pid'.  If it is
Packit ae235b
 * non-zero then the process is running, with that pid.
Packit ae235b
 *
Packit ae235b
 * When a GSubprocess is first created with g_object_new() it is not
Packit ae235b
 * running.  When it is finalized, it is also not running.
Packit ae235b
 *
Packit ae235b
 * During initable_init(), if the g_spawn() is successful then we
Packit ae235b
 * immediately register a child watch and take an extra ref on the
Packit ae235b
 * subprocess.  That reference doesn't drop until the child has quit,
Packit ae235b
 * which is why finalize can only happen in the non-running state.  In
Packit ae235b
 * the event that the g_spawn() failed we will still be finalizing a
Packit ae235b
 * non-running GSubprocess (before returning from g_subprocess_new())
Packit ae235b
 * with NULL.
Packit ae235b
 *
Packit ae235b
 * We make extensive use of the glib worker thread to guarantee
Packit ae235b
 * race-free operation.  As with all child watches, glib calls waitpid()
Packit ae235b
 * in the worker thread.  It reports the child exiting to us via the
Packit ae235b
 * worker thread (which means that we can do synchronous waits without
Packit ae235b
 * running a separate loop).  We also send signals to the child process
Packit ae235b
 * via the worker thread so that we don't race with waitpid() and
Packit ae235b
 * accidentally send a signal to an already-reaped child.
Packit ae235b
 */
Packit ae235b
static void initable_iface_init (GInitableIface         *initable_iface);
Packit ae235b
Packit ae235b
typedef GObjectClass GSubprocessClass;
Packit ae235b
Packit ae235b
struct _GSubprocess
Packit ae235b
{
Packit ae235b
  GObject parent;
Packit ae235b
Packit ae235b
  /* only used during construction */
Packit ae235b
  GSubprocessLauncher *launcher;
Packit ae235b
  GSubprocessFlags flags;
Packit ae235b
  gchar **argv;
Packit ae235b
Packit ae235b
  /* state tracking variables */
Packit ae235b
  gchar identifier[24];
Packit ae235b
  int status;
Packit ae235b
  GPid pid;
Packit ae235b
Packit ae235b
  /* list of GTask */
Packit ae235b
  GMutex pending_waits_lock;
Packit ae235b
  GSList *pending_waits;
Packit ae235b
Packit ae235b
  /* These are the streams created if a pipe is requested via flags. */
Packit ae235b
  GOutputStream *stdin_pipe;
Packit ae235b
  GInputStream  *stdout_pipe;
Packit ae235b
  GInputStream  *stderr_pipe;
Packit ae235b
};
Packit ae235b
Packit ae235b
G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
Packit ae235b
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))
Packit ae235b
Packit ae235b
enum
Packit ae235b
{
Packit ae235b
  PROP_0,
Packit ae235b
  PROP_FLAGS,
Packit ae235b
  PROP_ARGV,
Packit ae235b
  N_PROPS
Packit ae235b
};
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
typedef struct
Packit ae235b
{
Packit ae235b
  gint                 fds[3];
Packit ae235b
  GSpawnChildSetupFunc child_setup_func;
Packit ae235b
  gpointer             child_setup_data;
Packit ae235b
  GArray              *basic_fd_assignments;
Packit ae235b
  GArray              *needdup_fd_assignments;
Packit ae235b
} ChildData;
Packit ae235b
Packit ae235b
static void
Packit ae235b
unset_cloexec (int fd)
Packit ae235b
{
Packit ae235b
  int flags;
Packit ae235b
  int result;
Packit ae235b
Packit ae235b
  flags = fcntl (fd, F_GETFD, 0);
Packit ae235b
Packit ae235b
  if (flags != -1)
Packit ae235b
    {
Packit ae235b
      int errsv;
Packit ae235b
      flags &= (~FD_CLOEXEC);
Packit ae235b
      do
Packit ae235b
        {
Packit ae235b
          result = fcntl (fd, F_SETFD, flags);
Packit ae235b
          errsv = errno;
Packit ae235b
        }
Packit ae235b
      while (result == -1 && errsv == EINTR);
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static int
Packit ae235b
dupfd_cloexec (int parent_fd)
Packit ae235b
{
Packit ae235b
  int fd, errsv;
Packit ae235b
#ifdef F_DUPFD_CLOEXEC
Packit ae235b
  do
Packit ae235b
    {
Packit ae235b
      fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
Packit ae235b
      errsv = errno;
Packit ae235b
    }
Packit ae235b
  while (fd == -1 && errsv == EINTR);
Packit ae235b
#else
Packit ae235b
  /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
Packit ae235b
   * https://bugzilla.gnome.org/show_bug.cgi?id=710962
Packit ae235b
   */
Packit ae235b
  int result, flags;
Packit ae235b
  do
Packit ae235b
    {
Packit ae235b
      fd = fcntl (parent_fd, F_DUPFD, 3);
Packit ae235b
      errsv = errno;
Packit ae235b
    }
Packit ae235b
  while (fd == -1 && errsv == EINTR);
Packit ae235b
  flags = fcntl (fd, F_GETFD, 0);
Packit ae235b
  if (flags != -1)
Packit ae235b
    {
Packit ae235b
      flags |= FD_CLOEXEC;
Packit ae235b
      do
Packit ae235b
        {
Packit ae235b
          result = fcntl (fd, F_SETFD, flags);
Packit ae235b
          errsv = errno;
Packit ae235b
        }
Packit ae235b
      while (result == -1 && errsv == EINTR);
Packit ae235b
    }
Packit ae235b
#endif
Packit ae235b
  return fd;
Packit ae235b
}
Packit ae235b
Packit ae235b
/*
Packit ae235b
 * Based on code derived from
Packit ae235b
 * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
Packit ae235b
 * used under the LGPLv2+ with permission from author.
Packit ae235b
 */
Packit ae235b
static void
Packit ae235b
child_setup (gpointer user_data)
Packit ae235b
{
Packit ae235b
  ChildData *child_data = user_data;
Packit ae235b
  gint i;
Packit ae235b
  gint result;
Packit ae235b
  int errsv;
Packit ae235b
Packit ae235b
  /* We're on the child side now.  "Rename" the file descriptors in
Packit ae235b
   * child_data.fds[] to stdin/stdout/stderr.
Packit ae235b
   *
Packit ae235b
   * We don't close the originals.  It's possible that the originals
Packit ae235b
   * should not be closed and if they should be closed then they should
Packit ae235b
   * have been created O_CLOEXEC.
Packit ae235b
   */
Packit ae235b
  for (i = 0; i < 3; i++)
Packit ae235b
    if (child_data->fds[i] != -1 && child_data->fds[i] != i)
Packit ae235b
      {
Packit ae235b
        do
Packit ae235b
          {
Packit ae235b
            result = dup2 (child_data->fds[i], i);
Packit ae235b
            errsv = errno;
Packit ae235b
          }
Packit ae235b
        while (result == -1 && errsv == EINTR);
Packit ae235b
      }
Packit ae235b
Packit ae235b
  /* Basic fd assignments we can just unset FD_CLOEXEC */
Packit ae235b
  if (child_data->basic_fd_assignments)
Packit ae235b
    {
Packit ae235b
      for (i = 0; i < child_data->basic_fd_assignments->len; i++)
Packit ae235b
        {
Packit ae235b
          gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
Packit ae235b
Packit ae235b
          unset_cloexec (fd);
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
Packit ae235b
  /* If we're doing remapping fd assignments, we need to handle
Packit ae235b
   * the case where the user has specified e.g.:
Packit ae235b
   * 5 -> 4, 4 -> 6
Packit ae235b
   *
Packit ae235b
   * We do this by duping the source fds temporarily.
Packit ae235b
   */ 
Packit ae235b
  if (child_data->needdup_fd_assignments)
Packit ae235b
    {
Packit ae235b
      for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
Packit ae235b
        {
Packit ae235b
          gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
Packit ae235b
          gint new_parent_fd;
Packit ae235b
Packit ae235b
          new_parent_fd = dupfd_cloexec (parent_fd);
Packit ae235b
Packit ae235b
          g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
Packit ae235b
        }
Packit ae235b
      for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
Packit ae235b
        {
Packit ae235b
          gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
Packit ae235b
          gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
Packit ae235b
Packit ae235b
          if (parent_fd == child_fd)
Packit ae235b
            {
Packit ae235b
              unset_cloexec (parent_fd);
Packit ae235b
            }
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              do
Packit ae235b
                {
Packit ae235b
                  result = dup2 (parent_fd, child_fd);
Packit ae235b
                  errsv = errno;
Packit ae235b
                }
Packit ae235b
              while (result == -1 && errsv == EINTR);
Packit ae235b
              (void) close (parent_fd);
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (child_data->child_setup_func)
Packit ae235b
    child_data->child_setup_func (child_data->child_setup_data);
Packit ae235b
}
Packit ae235b
#endif
Packit ae235b
Packit ae235b
static GInputStream *
Packit ae235b
platform_input_stream_from_spawn_fd (gint fd)
Packit ae235b
{
Packit ae235b
  if (fd < 0)
Packit ae235b
    return NULL;
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  return g_unix_input_stream_new (fd, TRUE);
Packit ae235b
#else
Packit ae235b
  return g_win32_input_stream_new_from_fd (fd, TRUE);
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
static GOutputStream *
Packit ae235b
platform_output_stream_from_spawn_fd (gint fd)
Packit ae235b
{
Packit ae235b
  if (fd < 0)
Packit ae235b
    return NULL;
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  return g_unix_output_stream_new (fd, TRUE);
Packit ae235b
#else
Packit ae235b
  return g_win32_output_stream_new_from_fd (fd, TRUE);
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
static gint
Packit ae235b
unix_open_file (const char  *filename,
Packit ae235b
                gint         mode,
Packit ae235b
                GError     **error)
Packit ae235b
{
Packit ae235b
  gint my_fd;
Packit ae235b
Packit ae235b
  my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
Packit ae235b
Packit ae235b
  /* If we return -1 we should also set the error */
Packit ae235b
  if (my_fd < 0)
Packit ae235b
    {
Packit ae235b
      gint saved_errno = errno;
Packit ae235b
      char *display_name;
Packit ae235b
Packit ae235b
      display_name = g_filename_display_name (filename);
Packit ae235b
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
Packit ae235b
                   _("Error opening file “%s”: %s"), display_name,
Packit ae235b
                   g_strerror (saved_errno));
Packit ae235b
      g_free (display_name);
Packit ae235b
      /* fall through... */
Packit ae235b
    }
Packit ae235b
#ifndef HAVE_O_CLOEXEC
Packit ae235b
  else
Packit ae235b
    fcntl (my_fd, F_SETFD, FD_CLOEXEC);
Packit ae235b
#endif
Packit ae235b
Packit ae235b
  return my_fd;
Packit ae235b
}
Packit ae235b
#endif
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_set_property (GObject      *object,
Packit ae235b
                           guint         prop_id,
Packit ae235b
                           const GValue *value,
Packit ae235b
                           GParamSpec   *pspec)
Packit ae235b
{
Packit ae235b
  GSubprocess *self = G_SUBPROCESS (object);
Packit ae235b
Packit ae235b
  switch (prop_id)
Packit ae235b
    {
Packit ae235b
    case PROP_FLAGS:
Packit ae235b
      self->flags = g_value_get_flags (value);
Packit ae235b
      break;
Packit ae235b
Packit ae235b
    case PROP_ARGV:
Packit ae235b
      self->argv = g_value_dup_boxed (value);
Packit ae235b
      break;
Packit ae235b
Packit ae235b
    default:
Packit ae235b
      g_assert_not_reached ();
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
g_subprocess_exited (GPid     pid,
Packit ae235b
                     gint     status,
Packit ae235b
                     gpointer user_data)
Packit ae235b
{
Packit ae235b
  GSubprocess *self = user_data;
Packit ae235b
  GSList *tasks;
Packit ae235b
Packit ae235b
  g_assert (self->pid == pid);
Packit ae235b
Packit ae235b
  g_mutex_lock (&self->pending_waits_lock);
Packit ae235b
  self->status = status;
Packit ae235b
  tasks = self->pending_waits;
Packit ae235b
  self->pending_waits = NULL;
Packit ae235b
  self->pid = 0;
Packit ae235b
  g_mutex_unlock (&self->pending_waits_lock);
Packit ae235b
Packit ae235b
  /* Signal anyone in g_subprocess_wait_async() to wake up now */
Packit ae235b
  while (tasks)
Packit ae235b
    {
Packit ae235b
      g_task_return_boolean (tasks->data, TRUE);
Packit ae235b
      g_object_unref (tasks->data);
Packit ae235b
      tasks = g_slist_delete_link (tasks, tasks);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_spawn_close_pid (pid);
Packit ae235b
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
initable_init (GInitable     *initable,
Packit ae235b
               GCancellable  *cancellable,
Packit ae235b
               GError       **error)
Packit ae235b
{
Packit ae235b
  GSubprocess *self = G_SUBPROCESS (initable);
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  ChildData child_data = { { -1, -1, -1 }, 0 };
Packit ae235b
#endif
Packit ae235b
  gint *pipe_ptrs[3] = { NULL, NULL, NULL };
Packit ae235b
  gint pipe_fds[3] = { -1, -1, -1 };
Packit ae235b
  gint close_fds[3] = { -1, -1, -1 };
Packit ae235b
  GSpawnFlags spawn_flags = 0;
Packit ae235b
  gboolean success = FALSE;
Packit ae235b
  gint i;
Packit ae235b
Packit ae235b
  /* this is a programmer error */
Packit ae235b
  if (!self->argv || !self->argv[0] || !self->argv[0][0])
Packit ae235b
    return FALSE;
Packit ae235b
Packit ae235b
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
Packit ae235b
    return FALSE;
Packit ae235b
Packit ae235b
  /* We must setup the three fds that will end up in the child as stdin,
Packit ae235b
   * stdout and stderr.
Packit ae235b
   *
Packit ae235b
   * First, stdin.
Packit ae235b
   */
Packit ae235b
  if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
Packit ae235b
    spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
Packit ae235b
  else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
Packit ae235b
    pipe_ptrs[0] = &pipe_fds[0];
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  else if (self->launcher)
Packit ae235b
    {
Packit ae235b
      if (self->launcher->stdin_fd != -1)
Packit ae235b
        child_data.fds[0] = self->launcher->stdin_fd;
Packit ae235b
      else if (self->launcher->stdin_path != NULL)
Packit ae235b
        {
Packit ae235b
          child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
Packit ae235b
          if (child_data.fds[0] == -1)
Packit ae235b
            goto out;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
#endif
Packit ae235b
Packit ae235b
  /* Next, stdout. */
Packit ae235b
  if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
Packit ae235b
    spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
Packit ae235b
  else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
Packit ae235b
    pipe_ptrs[1] = &pipe_fds[1];
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  else if (self->launcher)
Packit ae235b
    {
Packit ae235b
      if (self->launcher->stdout_fd != -1)
Packit ae235b
        child_data.fds[1] = self->launcher->stdout_fd;
Packit ae235b
      else if (self->launcher->stdout_path != NULL)
Packit ae235b
        {
Packit ae235b
          child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
Packit ae235b
          if (child_data.fds[1] == -1)
Packit ae235b
            goto out;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
#endif
Packit ae235b
Packit ae235b
  /* Finally, stderr. */
Packit ae235b
  if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
Packit ae235b
    spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
Packit ae235b
  else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
Packit ae235b
    pipe_ptrs[2] = &pipe_fds[2];
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
Packit ae235b
    /* This will work because stderr gets setup after stdout. */
Packit ae235b
    child_data.fds[2] = 1;
Packit ae235b
  else if (self->launcher)
Packit ae235b
    {
Packit ae235b
      if (self->launcher->stderr_fd != -1)
Packit ae235b
        child_data.fds[2] = self->launcher->stderr_fd;
Packit ae235b
      else if (self->launcher->stderr_path != NULL)
Packit ae235b
        {
Packit ae235b
          child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
Packit ae235b
          if (child_data.fds[2] == -1)
Packit ae235b
            goto out;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  if (self->launcher)
Packit ae235b
    {
Packit ae235b
      child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
Packit ae235b
      child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
Packit ae235b
    }
Packit ae235b
#endif
Packit ae235b
Packit ae235b
  /* argv0 has no '/' in it?  We better do a PATH lookup. */
Packit ae235b
  if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
Packit ae235b
    {
Packit ae235b
      if (self->launcher && self->launcher->path_from_envp)
Packit ae235b
        spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
Packit ae235b
      else
Packit ae235b
        spawn_flags |= G_SPAWN_SEARCH_PATH;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
Packit ae235b
    spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
Packit ae235b
Packit ae235b
  spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
Packit ae235b
  spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
Packit ae235b
  child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
Packit ae235b
#endif
Packit ae235b
Packit ae235b
  success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
Packit ae235b
                                      self->argv,
Packit ae235b
                                      self->launcher ? self->launcher->envp : NULL,
Packit ae235b
                                      spawn_flags,
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
                                      child_setup, &child_data,
Packit ae235b
#else
Packit ae235b
                                      NULL, NULL,
Packit ae235b
#endif
Packit ae235b
                                      &self->pid,
Packit ae235b
                                      pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
Packit ae235b
                                      error);
Packit ae235b
  g_assert (success == (self->pid != 0));
Packit ae235b
Packit ae235b
  {
Packit ae235b
    guint64 identifier;
Packit ae235b
    gint s;
Packit ae235b
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
    identifier = (guint64) GetProcessId (self->pid);
Packit ae235b
#else
Packit ae235b
    identifier = (guint64) self->pid;
Packit ae235b
#endif
Packit ae235b
Packit ae235b
    s = g_snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
Packit ae235b
    g_assert (0 < s && s < sizeof self->identifier);
Packit ae235b
  }
Packit ae235b
Packit ae235b
  /* Start attempting to reap the child immediately */
Packit ae235b
  if (success)
Packit ae235b
    {
Packit ae235b
      GMainContext *worker_context;
Packit ae235b
      GSource *source;
Packit ae235b
Packit ae235b
      worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
Packit ae235b
      source = g_child_watch_source_new (self->pid);
Packit ae235b
      g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
Packit ae235b
      g_source_attach (source, worker_context);
Packit ae235b
      g_source_unref (source);
Packit ae235b
    }
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
out:
Packit ae235b
#endif
Packit ae235b
  /* we don't need this past init... */
Packit ae235b
  self->launcher = NULL;
Packit ae235b
Packit ae235b
  for (i = 0; i < 3; i++)
Packit ae235b
    if (close_fds[i] != -1)
Packit ae235b
      close (close_fds[i]);
Packit ae235b
Packit ae235b
  self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
Packit ae235b
  self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
Packit ae235b
  self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
Packit ae235b
Packit ae235b
  return success;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_finalize (GObject *object)
Packit ae235b
{
Packit ae235b
  GSubprocess *self = G_SUBPROCESS (object);
Packit ae235b
Packit ae235b
  g_assert (self->pending_waits == NULL);
Packit ae235b
  g_assert (self->pid == 0);
Packit ae235b
Packit ae235b
  g_clear_object (&self->stdin_pipe);
Packit ae235b
  g_clear_object (&self->stdout_pipe);
Packit ae235b
  g_clear_object (&self->stderr_pipe);
Packit ae235b
  g_strfreev (self->argv);
Packit ae235b
Packit ae235b
  g_mutex_clear (&self->pending_waits_lock);
Packit ae235b
Packit ae235b
  G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_init (GSubprocess  *self)
Packit ae235b
{
Packit ae235b
  g_mutex_init (&self->pending_waits_lock);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
initable_iface_init (GInitableIface *initable_iface)
Packit ae235b
{
Packit ae235b
  initable_iface->init = initable_init;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_class_init (GSubprocessClass *class)
Packit ae235b
{
Packit ae235b
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);
Packit ae235b
Packit ae235b
  gobject_class->finalize = g_subprocess_finalize;
Packit ae235b
  gobject_class->set_property = g_subprocess_set_property;
Packit ae235b
Packit ae235b
  g_object_class_install_property (gobject_class, PROP_FLAGS,
Packit ae235b
                                   g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
Packit ae235b
                                                       G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
Packit ae235b
                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
Packit ae235b
  g_object_class_install_property (gobject_class, PROP_ARGV,
Packit ae235b
                                   g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
Packit ae235b
                                                       G_TYPE_STRV, G_PARAM_WRITABLE |
Packit ae235b
                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_new: (skip)
Packit ae235b
 * @flags: flags that define the behaviour of the subprocess
Packit ae235b
 * @error: (nullable): return location for an error, or %NULL
Packit ae235b
 * @argv0: first commandline argument to pass to the subprocess
Packit ae235b
 * @...:   more commandline arguments, followed by %NULL
Packit ae235b
 *
Packit ae235b
 * Create a new process with the given flags and varargs argument
Packit ae235b
 * list.  By default, matching the g_spawn_async() defaults, the
Packit ae235b
 * child's stdin will be set to the system null device, and
Packit ae235b
 * stdout/stderr will be inherited from the parent.  You can use
Packit ae235b
 * @flags to control this behavior.
Packit ae235b
 *
Packit ae235b
 * The argument list must be terminated with %NULL.
Packit ae235b
 *
Packit ae235b
 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
Packit ae235b
 *   will be set)
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
GSubprocess *
Packit ae235b
g_subprocess_new (GSubprocessFlags   flags,
Packit ae235b
                  GError           **error,
Packit ae235b
                  const gchar       *argv0,
Packit ae235b
                  ...)
Packit ae235b
{
Packit ae235b
  GSubprocess *result;
Packit ae235b
  GPtrArray *args;
Packit ae235b
  const gchar *arg;
Packit ae235b
  va_list ap;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
Packit ae235b
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Packit ae235b
Packit ae235b
  args = g_ptr_array_new ();
Packit ae235b
Packit ae235b
  va_start (ap, argv0);
Packit ae235b
  g_ptr_array_add (args, (gchar *) argv0);
Packit ae235b
  while ((arg = va_arg (ap, const gchar *)))
Packit ae235b
    g_ptr_array_add (args, (gchar *) arg);
Packit ae235b
  g_ptr_array_add (args, NULL);
Packit ae235b
  va_end (ap);
Packit ae235b
Packit ae235b
  result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
Packit ae235b
Packit ae235b
  g_ptr_array_free (args, TRUE);
Packit ae235b
Packit ae235b
  return result;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_newv: (rename-to g_subprocess_new)
Packit ae235b
 * @argv: (array zero-terminated=1) (element-type filename): commandline arguments for the subprocess
Packit ae235b
 * @flags: flags that define the behaviour of the subprocess
Packit ae235b
 * @error: (nullable): return location for an error, or %NULL
Packit ae235b
 *
Packit ae235b
 * Create a new process with the given flags and argument list.
Packit ae235b
 *
Packit ae235b
 * The argument list is expected to be %NULL-terminated.
Packit ae235b
 *
Packit ae235b
 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
Packit ae235b
 *   will be set)
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
GSubprocess *
Packit ae235b
g_subprocess_newv (const gchar * const  *argv,
Packit ae235b
                   GSubprocessFlags      flags,
Packit ae235b
                   GError              **error)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
Packit ae235b
Packit ae235b
  return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
Packit ae235b
                         "argv", argv,
Packit ae235b
                         "flags", flags,
Packit ae235b
                         NULL);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_identifier:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * On UNIX, returns the process ID as a decimal string.
Packit ae235b
 * On Windows, returns the result of GetProcessId() also as a string.
Packit ae235b
 */
Packit ae235b
const gchar *
Packit ae235b
g_subprocess_get_identifier (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
Packit ae235b
Packit ae235b
  if (subprocess->pid)
Packit ae235b
    return subprocess->identifier;
Packit ae235b
  else
Packit ae235b
    return NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_stdin_pipe:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Gets the #GOutputStream that you can write to in order to give data
Packit ae235b
 * to the stdin of @subprocess.
Packit ae235b
 *
Packit ae235b
 * The process must have been created with
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
Packit ae235b
 *
Packit ae235b
 * Returns: (transfer none): the stdout pipe
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
GOutputStream *
Packit ae235b
g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
Packit ae235b
  g_return_val_if_fail (subprocess->stdin_pipe, NULL);
Packit ae235b
Packit ae235b
  return subprocess->stdin_pipe;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_stdout_pipe:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Gets the #GInputStream from which to read the stdout output of
Packit ae235b
 * @subprocess.
Packit ae235b
 *
Packit ae235b
 * The process must have been created with
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
Packit ae235b
 *
Packit ae235b
 * Returns: (transfer none): the stdout pipe
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
GInputStream *
Packit ae235b
g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
Packit ae235b
  g_return_val_if_fail (subprocess->stdout_pipe, NULL);
Packit ae235b
Packit ae235b
  return subprocess->stdout_pipe;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_stderr_pipe:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Gets the #GInputStream from which to read the stderr output of
Packit ae235b
 * @subprocess.
Packit ae235b
 *
Packit ae235b
 * The process must have been created with
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
Packit ae235b
 *
Packit ae235b
 * Returns: (transfer none): the stderr pipe
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
GInputStream *
Packit ae235b
g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
Packit ae235b
  g_return_val_if_fail (subprocess->stderr_pipe, NULL);
Packit ae235b
Packit ae235b
  return subprocess->stderr_pipe;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* Remove the first list element containing @data, and return %TRUE. If no
Packit ae235b
 * such element is found, return %FALSE. */
Packit ae235b
static gboolean
Packit ae235b
slist_remove_if_present (GSList        **list,
Packit ae235b
                         gconstpointer   data)
Packit ae235b
{
Packit ae235b
  GSList *l, *prev;
Packit ae235b
Packit ae235b
  for (l = *list, prev = NULL; l != NULL; prev = l, l = prev->next)
Packit ae235b
    {
Packit ae235b
      if (l->data == data)
Packit ae235b
        {
Packit ae235b
          if (prev != NULL)
Packit ae235b
            prev->next = l->next;
Packit ae235b
          else
Packit ae235b
            *list = l->next;
Packit ae235b
Packit ae235b
          g_slist_free_1 (l);
Packit ae235b
Packit ae235b
          return TRUE;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_wait_cancelled (GCancellable *cancellable,
Packit ae235b
                             gpointer      user_data)
Packit ae235b
{
Packit ae235b
  GTask *task = user_data;
Packit ae235b
  GSubprocess *self;
Packit ae235b
  gboolean task_was_pending;
Packit ae235b
Packit ae235b
  self = g_task_get_source_object (task);
Packit ae235b
Packit ae235b
  g_mutex_lock (&self->pending_waits_lock);
Packit ae235b
  task_was_pending = slist_remove_if_present (&self->pending_waits, task);
Packit ae235b
  g_mutex_unlock (&self->pending_waits_lock);
Packit ae235b
Packit ae235b
  if (task_was_pending)
Packit ae235b
    {
Packit ae235b
      g_task_return_boolean (task, FALSE);
Packit ae235b
      g_object_unref (task);  /* ref from pending_waits */
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait_async:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @cancellable: a #GCancellable, or %NULL
Packit ae235b
 * @callback: a #GAsyncReadyCallback to call when the operation is complete
Packit ae235b
 * @user_data: user_data for @callback
Packit ae235b
 *
Packit ae235b
 * Wait for the subprocess to terminate.
Packit ae235b
 *
Packit ae235b
 * This is the asynchronous version of g_subprocess_wait().
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_subprocess_wait_async (GSubprocess         *subprocess,
Packit ae235b
                         GCancellable        *cancellable,
Packit ae235b
                         GAsyncReadyCallback  callback,
Packit ae235b
                         gpointer             user_data)
Packit ae235b
{
Packit ae235b
  GTask *task;
Packit ae235b
Packit ae235b
  task = g_task_new (subprocess, cancellable, callback, user_data);
Packit ae235b
  g_task_set_source_tag (task, g_subprocess_wait_async);
Packit ae235b
Packit ae235b
  g_mutex_lock (&subprocess->pending_waits_lock);
Packit ae235b
  if (subprocess->pid)
Packit ae235b
    {
Packit ae235b
      /* Only bother with cancellable if we're putting it in the list.
Packit ae235b
       * If not, it's going to dispatch immediately anyway and we will
Packit ae235b
       * see the cancellation in the _finish().
Packit ae235b
       */
Packit ae235b
      if (cancellable)
Packit ae235b
        g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
Packit ae235b
Packit ae235b
      subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
Packit ae235b
      task = NULL;
Packit ae235b
    }
Packit ae235b
  g_mutex_unlock (&subprocess->pending_waits_lock);
Packit ae235b
Packit ae235b
  /* If we still have task then it's because did_exit is already TRUE */
Packit ae235b
  if (task != NULL)
Packit ae235b
    {
Packit ae235b
      g_task_return_boolean (task, TRUE);
Packit ae235b
      g_object_unref (task);
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait_finish:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
Packit ae235b
 * @error: a pointer to a %NULL #GError, or %NULL
Packit ae235b
 *
Packit ae235b
 * Collects the result of a previous call to
Packit ae235b
 * g_subprocess_wait_async().
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if successful, or %FALSE with @error set
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_wait_finish (GSubprocess   *subprocess,
Packit ae235b
                          GAsyncResult  *result,
Packit ae235b
                          GError       **error)
Packit ae235b
{
Packit ae235b
  return g_task_propagate_boolean (G_TASK (result), error);
Packit ae235b
}
Packit ae235b
Packit ae235b
/* Some generic helpers for emulating synchronous operations using async
Packit ae235b
 * operations.
Packit ae235b
 */
Packit ae235b
static void
Packit ae235b
g_subprocess_sync_setup (void)
Packit ae235b
{
Packit ae235b
  g_main_context_push_thread_default (g_main_context_new ());
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_sync_done (GObject      *source_object,
Packit ae235b
                        GAsyncResult *result,
Packit ae235b
                        gpointer      user_data)
Packit ae235b
{
Packit ae235b
  GAsyncResult **result_ptr = user_data;
Packit ae235b
Packit ae235b
  *result_ptr = g_object_ref (result);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_sync_complete (GAsyncResult **result)
Packit ae235b
{
Packit ae235b
  GMainContext *context = g_main_context_get_thread_default ();
Packit ae235b
Packit ae235b
  while (!*result)
Packit ae235b
    g_main_context_iteration (context, TRUE);
Packit ae235b
Packit ae235b
  g_main_context_pop_thread_default (context);
Packit ae235b
  g_main_context_unref (context);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @cancellable: a #GCancellable
Packit ae235b
 * @error: a #GError
Packit ae235b
 *
Packit ae235b
 * Synchronously wait for the subprocess to terminate.
Packit ae235b
 *
Packit ae235b
 * After the process terminates you can query its exit status with
Packit ae235b
 * functions such as g_subprocess_get_if_exited() and
Packit ae235b
 * g_subprocess_get_exit_status().
Packit ae235b
 *
Packit ae235b
 * This function does not fail in the case of the subprocess having
Packit ae235b
 * abnormal termination.  See g_subprocess_wait_check() for that.
Packit ae235b
 *
Packit ae235b
 * Cancelling @cancellable doesn't kill the subprocess.  Call
Packit ae235b
 * g_subprocess_force_exit() if it is desirable.
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_wait (GSubprocess   *subprocess,
Packit ae235b
                   GCancellable  *cancellable,
Packit ae235b
                   GError       **error)
Packit ae235b
{
Packit ae235b
  GAsyncResult *result = NULL;
Packit ae235b
  gboolean success;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
Packit ae235b
  /* Synchronous waits are actually the 'more difficult' case because we
Packit ae235b
   * need to deal with the possibility of cancellation.  That more or
Packit ae235b
   * less implies that we need a main context (to dispatch either of the
Packit ae235b
   * possible reasons for the operation ending).
Packit ae235b
   *
Packit ae235b
   * So we make one and then do this async...
Packit ae235b
   */
Packit ae235b
Packit ae235b
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
Packit ae235b
    return FALSE;
Packit ae235b
Packit ae235b
  /* We can shortcut in the case that the process already quit (but only
Packit ae235b
   * after we checked the cancellable).
Packit ae235b
   */
Packit ae235b
  if (subprocess->pid == 0)
Packit ae235b
    return TRUE;
Packit ae235b
Packit ae235b
  /* Otherwise, we need to do this the long way... */
Packit ae235b
  g_subprocess_sync_setup ();
Packit ae235b
  g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
Packit ae235b
  g_subprocess_sync_complete (&result);
Packit ae235b
  success = g_subprocess_wait_finish (subprocess, result, error);
Packit ae235b
  g_object_unref (result);
Packit ae235b
Packit ae235b
  return success;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait_check:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @cancellable: a #GCancellable
Packit ae235b
 * @error: a #GError
Packit ae235b
 *
Packit ae235b
 * Combines g_subprocess_wait() with g_spawn_check_exit_status().
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE on success, %FALSE if process exited abnormally, or
Packit ae235b
 * @cancellable was cancelled
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_wait_check (GSubprocess   *subprocess,
Packit ae235b
                         GCancellable  *cancellable,
Packit ae235b
                         GError       **error)
Packit ae235b
{
Packit ae235b
  return g_subprocess_wait (subprocess, cancellable, error) &&
Packit ae235b
         g_spawn_check_exit_status (subprocess->status, error);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait_check_async:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @cancellable: a #GCancellable, or %NULL
Packit ae235b
 * @callback: a #GAsyncReadyCallback to call when the operation is complete
Packit ae235b
 * @user_data: user_data for @callback
Packit ae235b
 *
Packit ae235b
 * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
Packit ae235b
 *
Packit ae235b
 * This is the asynchronous version of g_subprocess_wait_check().
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_subprocess_wait_check_async (GSubprocess         *subprocess,
Packit ae235b
                               GCancellable        *cancellable,
Packit ae235b
                               GAsyncReadyCallback  callback,
Packit ae235b
                               gpointer             user_data)
Packit ae235b
{
Packit ae235b
  g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_wait_check_finish:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
Packit ae235b
 * @error: a pointer to a %NULL #GError, or %NULL
Packit ae235b
 *
Packit ae235b
 * Collects the result of a previous call to
Packit ae235b
 * g_subprocess_wait_check_async().
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if successful, or %FALSE with @error set
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_wait_check_finish (GSubprocess   *subprocess,
Packit ae235b
                                GAsyncResult  *result,
Packit ae235b
                                GError       **error)
Packit ae235b
{
Packit ae235b
  return g_subprocess_wait_finish (subprocess, result, error) &&
Packit ae235b
         g_spawn_check_exit_status (subprocess->status, error);
Packit ae235b
}
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
typedef struct
Packit ae235b
{
Packit ae235b
  GSubprocess *subprocess;
Packit ae235b
  gint signalnum;
Packit ae235b
} SignalRecord;
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
g_subprocess_actually_send_signal (gpointer user_data)
Packit ae235b
{
Packit ae235b
  SignalRecord *signal_record = user_data;
Packit ae235b
Packit ae235b
  /* The pid is set to zero from the worker thread as well, so we don't
Packit ae235b
   * need to take a lock in order to prevent it from changing under us.
Packit ae235b
   */
Packit ae235b
  if (signal_record->subprocess->pid)
Packit ae235b
    kill (signal_record->subprocess->pid, signal_record->signalnum);
Packit ae235b
Packit ae235b
  g_object_unref (signal_record->subprocess);
Packit ae235b
Packit ae235b
  g_slice_free (SignalRecord, signal_record);
Packit ae235b
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_dispatch_signal (GSubprocess *subprocess,
Packit ae235b
                              gint         signalnum)
Packit ae235b
{
Packit ae235b
  SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
Packit ae235b
Packit ae235b
  g_return_if_fail (G_IS_SUBPROCESS (subprocess));
Packit ae235b
Packit ae235b
  /* This MUST be a lower priority than the priority that the child
Packit ae235b
   * watch source uses in initable_init().
Packit ae235b
   *
Packit ae235b
   * Reaping processes, reporting the results back to GSubprocess and
Packit ae235b
   * sending signals is all done in the glib worker thread.  We cannot
Packit ae235b
   * have a kill() done after the reap and before the report without
Packit ae235b
   * risking killing a process that's no longer there so the kill()
Packit ae235b
   * needs to have the lower priority.
Packit ae235b
   *
Packit ae235b
   * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
Packit ae235b
   */
Packit ae235b
  g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
Packit ae235b
                              G_PRIORITY_HIGH_IDLE,
Packit ae235b
                              g_subprocess_actually_send_signal,
Packit ae235b
                              g_slice_dup (SignalRecord, &signal_record),
Packit ae235b
                              NULL);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_send_signal:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @signal_num: the signal number to send
Packit ae235b
 *
Packit ae235b
 * Sends the UNIX signal @signal_num to the subprocess, if it is still
Packit ae235b
 * running.
Packit ae235b
 *
Packit ae235b
 * This API is race-free.  If the subprocess has terminated, it will not
Packit ae235b
 * be signalled.
Packit ae235b
 *
Packit ae235b
 * This API is not available on Windows.
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
void
Packit ae235b
g_subprocess_send_signal (GSubprocess *subprocess,
Packit ae235b
                          gint         signal_num)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_SUBPROCESS (subprocess));
Packit ae235b
Packit ae235b
  g_subprocess_dispatch_signal (subprocess, signal_num);
Packit ae235b
}
Packit ae235b
#endif
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_force_exit:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Use an operating-system specific method to attempt an immediate,
Packit ae235b
 * forceful termination of the process.  There is no mechanism to
Packit ae235b
 * determine whether or not the request itself was successful;
Packit ae235b
 * however, you can use g_subprocess_wait() to monitor the status of
Packit ae235b
 * the process after calling this function.
Packit ae235b
 *
Packit ae235b
 * On Unix, this function sends %SIGKILL.
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
void
Packit ae235b
g_subprocess_force_exit (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_SUBPROCESS (subprocess));
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  g_subprocess_dispatch_signal (subprocess, SIGKILL);
Packit ae235b
#else
Packit ae235b
  TerminateProcess (subprocess->pid, 1);
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_status:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Gets the raw status code of the process, as from waitpid().
Packit ae235b
 *
Packit ae235b
 * This value has no particular meaning, but it can be used with the
Packit ae235b
 * macros defined by the system headers such as WIFEXITED.  It can also
Packit ae235b
 * be used with g_spawn_check_exit_status().
Packit ae235b
 *
Packit ae235b
 * It is more likely that you want to use g_subprocess_get_if_exited()
Packit ae235b
 * followed by g_subprocess_get_exit_status().
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() has
Packit ae235b
 * returned.
Packit ae235b
 *
Packit ae235b
 * Returns: the (meaningless) waitpid() exit status from the kernel
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gint
Packit ae235b
g_subprocess_get_status (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, FALSE);
Packit ae235b
Packit ae235b
  return subprocess->status;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_successful:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Checks if the process was "successful".  A process is considered
Packit ae235b
 * successful if it exited cleanly with an exit status of 0, either by
Packit ae235b
 * way of the exit() system call or return from main().
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() has
Packit ae235b
 * returned.
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if the process exited cleanly with a exit status of 0
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gboolean
Packit ae235b
g_subprocess_get_successful (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, FALSE);
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
Packit ae235b
#else
Packit ae235b
  return subprocess->status == 0;
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_if_exited:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Check if the given subprocess exited normally (ie: by way of exit()
Packit ae235b
 * or return from main()).
Packit ae235b
 *
Packit ae235b
 * This is equivalent to the system WIFEXITED macro.
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() has
Packit ae235b
 * returned.
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if the case of a normal exit
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gboolean
Packit ae235b
g_subprocess_get_if_exited (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, FALSE);
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  return WIFEXITED (subprocess->status);
Packit ae235b
#else
Packit ae235b
  return TRUE;
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_exit_status:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Check the exit status of the subprocess, given that it exited
Packit ae235b
 * normally.  This is the value passed to the exit() system call or the
Packit ae235b
 * return value from main.
Packit ae235b
 *
Packit ae235b
 * This is equivalent to the system WEXITSTATUS macro.
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() and
Packit ae235b
 * unless g_subprocess_get_if_exited() returned %TRUE.
Packit ae235b
 *
Packit ae235b
 * Returns: the exit status
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gint
Packit ae235b
g_subprocess_get_exit_status (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, 1);
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
Packit ae235b
Packit ae235b
  return WEXITSTATUS (subprocess->status);
Packit ae235b
#else
Packit ae235b
  return subprocess->status;
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_if_signaled:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Check if the given subprocess terminated in response to a signal.
Packit ae235b
 *
Packit ae235b
 * This is equivalent to the system WIFSIGNALED macro.
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() has
Packit ae235b
 * returned.
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if the case of termination due to a signal
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gboolean
Packit ae235b
g_subprocess_get_if_signaled (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, FALSE);
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  return WIFSIGNALED (subprocess->status);
Packit ae235b
#else
Packit ae235b
  return FALSE;
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_get_term_sig:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 *
Packit ae235b
 * Get the signal number that caused the subprocess to terminate, given
Packit ae235b
 * that it terminated due to a signal.
Packit ae235b
 *
Packit ae235b
 * This is equivalent to the system WTERMSIG macro.
Packit ae235b
 *
Packit ae235b
 * It is an error to call this function before g_subprocess_wait() and
Packit ae235b
 * unless g_subprocess_get_if_signaled() returned %TRUE.
Packit ae235b
 *
Packit ae235b
 * Returns: the signal causing termination
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gint
Packit ae235b
g_subprocess_get_term_sig (GSubprocess *subprocess)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
Packit ae235b
  g_return_val_if_fail (subprocess->pid == 0, 0);
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
  g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
Packit ae235b
Packit ae235b
  return WTERMSIG (subprocess->status);
Packit ae235b
#else
Packit ae235b
  g_critical ("g_subprocess_get_term_sig() called on Windows, where "
Packit ae235b
              "g_subprocess_get_if_signaled() always returns FALSE...");
Packit ae235b
  return 0;
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
/*< private >*/
Packit ae235b
void
Packit ae235b
g_subprocess_set_launcher (GSubprocess         *subprocess,
Packit ae235b
                           GSubprocessLauncher *launcher)
Packit ae235b
{
Packit ae235b
  subprocess->launcher = launcher;
Packit ae235b
}
Packit ae235b
Packit ae235b
Packit ae235b
/* g_subprocess_communicate implementation below:
Packit ae235b
 *
Packit ae235b
 * This is a tough problem.  We have to watch 5 things at the same time:
Packit ae235b
 *
Packit ae235b
 *  - writing to stdin made progress
Packit ae235b
 *  - reading from stdout made progress
Packit ae235b
 *  - reading from stderr made progress
Packit ae235b
 *  - process terminated
Packit ae235b
 *  - cancellable being cancelled by caller
Packit ae235b
 *
Packit ae235b
 * We use a GMainContext for all of these (either as async function
Packit ae235b
 * calls or as a GSource (in the case of the cancellable).  That way at
Packit ae235b
 * least we don't have to worry about threading.
Packit ae235b
 *
Packit ae235b
 * For the sync case we use the usual trick of creating a private main
Packit ae235b
 * context and iterating it until completion.
Packit ae235b
 *
Packit ae235b
 * It's very possible that the process will dump a lot of data to stdout
Packit ae235b
 * just before it quits, so we can easily have data to read from stdout
Packit ae235b
 * and see the process has terminated at the same time.  We want to make
Packit ae235b
 * sure that we read all of the data from the pipes first, though, so we
Packit ae235b
 * do IO operations at a higher priority than the wait operation (which
Packit ae235b
 * is at G_IO_PRIORITY_DEFAULT).  Even in the case that we have to do
Packit ae235b
 * multiple reads to get this data, the pipe() will always be polling
Packit ae235b
 * as ready and with the async result for the read at a higher priority,
Packit ae235b
 * the main context will not dispatch the completion for the wait().
Packit ae235b
 *
Packit ae235b
 * We keep our own private GCancellable.  In the event that any of the
Packit ae235b
 * above suffers from an error condition (including the user cancelling
Packit ae235b
 * their cancellable) we immediately dispatch the GTask with the error
Packit ae235b
 * result and fire our cancellable to cleanup any pending operations.
Packit ae235b
 * In the case that the error is that the user's cancellable was fired,
Packit ae235b
 * it's vaguely wasteful to report an error because GTask will handle
Packit ae235b
 * this automatically, so we just return FALSE.
Packit ae235b
 *
Packit ae235b
 * We let each pending sub-operation take a ref on the GTask of the
Packit ae235b
 * communicate operation.  We have to be careful that we don't report
Packit ae235b
 * the task completion more than once, though, so we keep a flag for
Packit ae235b
 * that.
Packit ae235b
 */
Packit ae235b
typedef struct
Packit ae235b
{
Packit ae235b
  const gchar *stdin_data;
Packit ae235b
  gsize stdin_length;
Packit ae235b
  gsize stdin_offset;
Packit ae235b
Packit ae235b
  gboolean add_nul;
Packit ae235b
Packit ae235b
  GInputStream *stdin_buf;
Packit ae235b
  GMemoryOutputStream *stdout_buf;
Packit ae235b
  GMemoryOutputStream *stderr_buf;
Packit ae235b
Packit ae235b
  GCancellable *cancellable;
Packit ae235b
  GSource      *cancellable_source;
Packit ae235b
Packit ae235b
  guint         outstanding_ops;
Packit ae235b
  gboolean      reported_error;
Packit ae235b
} CommunicateState;
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_communicate_made_progress (GObject      *source_object,
Packit ae235b
                                        GAsyncResult *result,
Packit ae235b
                                        gpointer      user_data)
Packit ae235b
{
Packit ae235b
  CommunicateState *state;
Packit ae235b
  GSubprocess *subprocess;
Packit ae235b
  GError *error = NULL;
Packit ae235b
  gpointer source;
Packit ae235b
  GTask *task;
Packit ae235b
Packit ae235b
  g_assert (source_object != NULL);
Packit ae235b
Packit ae235b
  task = user_data;
Packit ae235b
  subprocess = g_task_get_source_object (task);
Packit ae235b
  state = g_task_get_task_data (task);
Packit ae235b
  source = source_object;
Packit ae235b
Packit ae235b
  state->outstanding_ops--;
Packit ae235b
Packit ae235b
  if (source == subprocess->stdin_pipe ||
Packit ae235b
      source == state->stdout_buf ||
Packit ae235b
      source == state->stderr_buf)
Packit ae235b
    {
Packit ae235b
      if (g_output_stream_splice_finish ((GOutputStream*) source, result, &error) == -1)
Packit ae235b
        goto out;
Packit ae235b
Packit ae235b
      if (source == state->stdout_buf ||
Packit ae235b
          source == state->stderr_buf)
Packit ae235b
        {
Packit ae235b
          /* This is a memory stream, so it can't be cancelled or return
Packit ae235b
           * an error really.
Packit ae235b
           */
Packit ae235b
          if (state->add_nul)
Packit ae235b
            {
Packit ae235b
              gsize bytes_written;
Packit ae235b
              if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
Packit ae235b
                                              NULL, &error))
Packit ae235b
                goto out;
Packit ae235b
            }
Packit ae235b
          if (!g_output_stream_close (source, NULL, &error))
Packit ae235b
            goto out;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  else if (source == subprocess)
Packit ae235b
    {
Packit ae235b
      (void) g_subprocess_wait_finish (subprocess, result, &error);
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    g_assert_not_reached ();
Packit ae235b
Packit ae235b
 out:
Packit ae235b
  if (error)
Packit ae235b
    {
Packit ae235b
      /* Only report the first error we see.
Packit ae235b
       *
Packit ae235b
       * We might be seeing an error as a result of the cancellation
Packit ae235b
       * done when the process quits.
Packit ae235b
       */
Packit ae235b
      if (!state->reported_error)
Packit ae235b
        {
Packit ae235b
          state->reported_error = TRUE;
Packit ae235b
          g_cancellable_cancel (state->cancellable);
Packit ae235b
          g_task_return_error (task, error);
Packit ae235b
        }
Packit ae235b
      else
Packit ae235b
        g_error_free (error);
Packit ae235b
    }
Packit ae235b
  else if (state->outstanding_ops == 0)
Packit ae235b
    {
Packit ae235b
      g_task_return_boolean (task, TRUE);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  /* And drop the original ref */
Packit ae235b
  g_object_unref (task);
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
g_subprocess_communicate_cancelled (gpointer user_data)
Packit ae235b
{
Packit ae235b
  CommunicateState *state = user_data;
Packit ae235b
Packit ae235b
  g_cancellable_cancel (state->cancellable);
Packit ae235b
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_subprocess_communicate_state_free (gpointer data)
Packit ae235b
{
Packit ae235b
  CommunicateState *state = data;
Packit ae235b
Packit ae235b
  g_clear_object (&state->cancellable);
Packit ae235b
  g_clear_object (&state->stdin_buf);
Packit ae235b
  g_clear_object (&state->stdout_buf);
Packit ae235b
  g_clear_object (&state->stderr_buf);
Packit ae235b
Packit ae235b
  if (state->cancellable_source)
Packit ae235b
    {
Packit ae235b
      g_source_destroy (state->cancellable_source);
Packit ae235b
      g_source_unref (state->cancellable_source);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_slice_free (CommunicateState, state);
Packit ae235b
}
Packit ae235b
Packit ae235b
static CommunicateState *
Packit ae235b
g_subprocess_communicate_internal (GSubprocess         *subprocess,
Packit ae235b
                                   gboolean             add_nul,
Packit ae235b
                                   GBytes              *stdin_buf,
Packit ae235b
                                   GCancellable        *cancellable,
Packit ae235b
                                   GAsyncReadyCallback  callback,
Packit ae235b
                                   gpointer             user_data)
Packit ae235b
{
Packit ae235b
  CommunicateState *state;
Packit ae235b
  GTask *task;
Packit ae235b
Packit ae235b
  task = g_task_new (subprocess, cancellable, callback, user_data);
Packit ae235b
  g_task_set_source_tag (task, g_subprocess_communicate_internal);
Packit ae235b
Packit ae235b
  state = g_slice_new0 (CommunicateState);
Packit ae235b
  g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
Packit ae235b
Packit ae235b
  state->cancellable = g_cancellable_new ();
Packit ae235b
  state->add_nul = add_nul;
Packit ae235b
Packit ae235b
  if (cancellable)
Packit ae235b
    {
Packit ae235b
      state->cancellable_source = g_cancellable_source_new (cancellable);
Packit ae235b
      /* No ref held here, but we unref the source from state's free function */
Packit ae235b
      g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
Packit ae235b
      g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (subprocess->stdin_pipe)
Packit ae235b
    {
Packit ae235b
      g_assert (stdin_buf != NULL);
Packit ae235b
      state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
Packit ae235b
      g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
Packit ae235b
                                    G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
Packit ae235b
                                    G_PRIORITY_DEFAULT, state->cancellable,
Packit ae235b
                                    g_subprocess_communicate_made_progress, g_object_ref (task));
Packit ae235b
      state->outstanding_ops++;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (subprocess->stdout_pipe)
Packit ae235b
    {
Packit ae235b
      state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
Packit ae235b
      g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
Packit ae235b
                                    G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
Packit ae235b
                                    G_PRIORITY_DEFAULT, state->cancellable,
Packit ae235b
                                    g_subprocess_communicate_made_progress, g_object_ref (task));
Packit ae235b
      state->outstanding_ops++;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (subprocess->stderr_pipe)
Packit ae235b
    {
Packit ae235b
      state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
Packit ae235b
      g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
Packit ae235b
                                    G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
Packit ae235b
                                    G_PRIORITY_DEFAULT, state->cancellable,
Packit ae235b
                                    g_subprocess_communicate_made_progress, g_object_ref (task));
Packit ae235b
      state->outstanding_ops++;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_subprocess_wait_async (subprocess, state->cancellable,
Packit ae235b
                           g_subprocess_communicate_made_progress, g_object_ref (task));
Packit ae235b
  state->outstanding_ops++;
Packit ae235b
Packit ae235b
  g_object_unref (task);
Packit ae235b
  return state;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
Packit ae235b
 * @cancellable: a #GCancellable
Packit ae235b
 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
Packit ae235b
 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
Packit ae235b
 * @error: a pointer to a %NULL #GError pointer, or %NULL
Packit ae235b
 *
Packit ae235b
 * Communicate with the subprocess until it terminates, and all input
Packit ae235b
 * and output has been completed.
Packit ae235b
 *
Packit ae235b
 * If @stdin_buf is given, the subprocess must have been created with
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDIN_PIPE.  The given data is fed to the
Packit ae235b
 * stdin of the subprocess and the pipe is closed (ie: EOF).
Packit ae235b
 *
Packit ae235b
 * At the same time (as not to cause blocking when dealing with large
Packit ae235b
 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
Packit ae235b
 * streams.  The data that was read is returned in @stdout and/or
Packit ae235b
 * the @stderr.
Packit ae235b
 *
Packit ae235b
 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
Packit ae235b
 * @stdout_buf will contain the data read from stdout.  Otherwise, for
Packit ae235b
 * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
Packit ae235b
 * @stdout_buf will be set to %NULL.  Similar provisions apply to
Packit ae235b
 * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
Packit ae235b
 *
Packit ae235b
 * As usual, any output variable may be given as %NULL to ignore it.
Packit ae235b
 *
Packit ae235b
 * If you desire the stdout and stderr data to be interleaved, create
Packit ae235b
 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
Packit ae235b
 * %G_SUBPROCESS_FLAGS_STDERR_MERGE.  The merged result will be returned
Packit ae235b
 * in @stdout_buf and @stderr_buf will be set to %NULL.
Packit ae235b
 *
Packit ae235b
 * In case of any error (including cancellation), %FALSE will be
Packit ae235b
 * returned with @error set.  Some or all of the stdin data may have
Packit ae235b
 * been written.  Any stdout or stderr data that has been read will be
Packit ae235b
 * discarded. None of the out variables (aside from @error) will have
Packit ae235b
 * been set to anything in particular and should not be inspected.
Packit ae235b
 *
Packit ae235b
 * In the case that %TRUE is returned, the subprocess has exited and the
Packit ae235b
 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
Packit ae235b
 * g_subprocess_get_exit_status()) may be used.
Packit ae235b
 *
Packit ae235b
 * You should not attempt to use any of the subprocess pipes after
Packit ae235b
 * starting this function, since they may be left in strange states,
Packit ae235b
 * even if the operation was cancelled.  You should especially not
Packit ae235b
 * attempt to interact with the pipes while the operation is in progress
Packit ae235b
 * (either from another thread or if using the asynchronous version).
Packit ae235b
 *
Packit ae235b
 * Returns: %TRUE if successful
Packit ae235b
 *
Packit ae235b
 * Since: 2.40
Packit ae235b
 **/
Packit ae235b
gboolean
Packit ae235b
g_subprocess_communicate (GSubprocess   *subprocess,
Packit ae235b
                          GBytes        *stdin_buf,
Packit ae235b
                          GCancellable  *cancellable,
Packit ae235b
                          GBytes       **stdout_buf,
Packit ae235b
                          GBytes       **stderr_buf,
Packit ae235b
                          GError       **error)
Packit ae235b
{
Packit ae235b
  GAsyncResult *result = NULL;
Packit ae235b
  gboolean success;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
Packit ae235b
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
Packit ae235b
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
Packit ae235b
Packit ae235b
  g_subprocess_sync_setup ();
Packit ae235b
  g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
Packit ae235b
                                     g_subprocess_sync_done, &result);
Packit ae235b
  g_subprocess_sync_complete (&result);
Packit ae235b
  success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
Packit ae235b
  g_object_unref (result);
Packit ae235b
Packit ae235b
  return success;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate_async:
Packit ae235b
 * @subprocess: Self
Packit ae235b
 * @stdin_buf: (nullable): Input data, or %NULL
Packit ae235b
 * @cancellable: (nullable): Cancellable
Packit ae235b
 * @callback: Callback
Packit ae235b
 * @user_data: User data
Packit ae235b
 *
Packit ae235b
 * Asynchronous version of g_subprocess_communicate().  Complete
Packit ae235b
 * invocation with g_subprocess_communicate_finish().
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_subprocess_communicate_async (GSubprocess         *subprocess,
Packit ae235b
                                GBytes              *stdin_buf,
Packit ae235b
                                GCancellable        *cancellable,
Packit ae235b
                                GAsyncReadyCallback  callback,
Packit ae235b
                                gpointer             user_data)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_SUBPROCESS (subprocess));
Packit ae235b
  g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
Packit ae235b
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
Packit ae235b
Packit ae235b
  g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate_finish:
Packit ae235b
 * @subprocess: Self
Packit ae235b
 * @result: Result
Packit ae235b
 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
Packit ae235b
 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
Packit ae235b
 * @error: Error
Packit ae235b
 *
Packit ae235b
 * Complete an invocation of g_subprocess_communicate_async().
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_communicate_finish (GSubprocess   *subprocess,
Packit ae235b
                                 GAsyncResult  *result,
Packit ae235b
                                 GBytes       **stdout_buf,
Packit ae235b
                                 GBytes       **stderr_buf,
Packit ae235b
                                 GError       **error)
Packit ae235b
{
Packit ae235b
  gboolean success;
Packit ae235b
  CommunicateState *state;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
Packit ae235b
Packit ae235b
  g_object_ref (result);
Packit ae235b
Packit ae235b
  state = g_task_get_task_data ((GTask*)result);
Packit ae235b
  success = g_task_propagate_boolean ((GTask*)result, error);
Packit ae235b
Packit ae235b
  if (success)
Packit ae235b
    {
Packit ae235b
      if (stdout_buf)
Packit ae235b
        *stdout_buf = (state->stdout_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stdout_buf) : NULL;
Packit ae235b
      if (stderr_buf)
Packit ae235b
        *stderr_buf = (state->stderr_buf != NULL) ? g_memory_output_stream_steal_as_bytes (state->stderr_buf) : NULL;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_object_unref (result);
Packit ae235b
  return success;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate_utf8:
Packit ae235b
 * @subprocess: a #GSubprocess
Packit ae235b
 * @stdin_buf: (nullable): data to send to the stdin of the subprocess, or %NULL
Packit ae235b
 * @cancellable: a #GCancellable
Packit ae235b
 * @stdout_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stdout
Packit ae235b
 * @stderr_buf: (out) (nullable) (optional) (transfer full): data read from the subprocess stderr
Packit ae235b
 * @error: a pointer to a %NULL #GError pointer, or %NULL
Packit ae235b
 *
Packit ae235b
 * Like g_subprocess_communicate(), but validates the output of the
Packit ae235b
 * process as UTF-8, and returns it as a regular NUL terminated string.
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_communicate_utf8 (GSubprocess   *subprocess,
Packit ae235b
                               const char    *stdin_buf,
Packit ae235b
                               GCancellable  *cancellable,
Packit ae235b
                               char         **stdout_buf,
Packit ae235b
                               char         **stderr_buf,
Packit ae235b
                               GError       **error)
Packit ae235b
{
Packit ae235b
  GAsyncResult *result = NULL;
Packit ae235b
  gboolean success;
Packit ae235b
  GBytes *stdin_bytes;
Packit ae235b
  size_t stdin_buf_len = 0;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
Packit ae235b
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
Packit ae235b
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
Packit ae235b
Packit ae235b
  if (stdin_buf != NULL)
Packit ae235b
    stdin_buf_len = strlen (stdin_buf);
Packit ae235b
  stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
Packit ae235b
Packit ae235b
  g_subprocess_sync_setup ();
Packit ae235b
  g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
Packit ae235b
                                     g_subprocess_sync_done, &result);
Packit ae235b
  g_subprocess_sync_complete (&result);
Packit ae235b
  success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
Packit ae235b
  g_object_unref (result);
Packit ae235b
Packit ae235b
  g_bytes_unref (stdin_bytes);
Packit ae235b
  return success;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate_utf8_async:
Packit ae235b
 * @subprocess: Self
Packit ae235b
 * @stdin_buf: (nullable): Input data, or %NULL
Packit ae235b
 * @cancellable: Cancellable
Packit ae235b
 * @callback: Callback
Packit ae235b
 * @user_data: User data
Packit ae235b
 *
Packit ae235b
 * Asynchronous version of g_subprocess_communicate_utf8().  Complete
Packit ae235b
 * invocation with g_subprocess_communicate_utf8_finish().
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_subprocess_communicate_utf8_async (GSubprocess         *subprocess,
Packit ae235b
                                     const char          *stdin_buf,
Packit ae235b
                                     GCancellable        *cancellable,
Packit ae235b
                                     GAsyncReadyCallback  callback,
Packit ae235b
                                     gpointer             user_data)
Packit ae235b
{
Packit ae235b
  GBytes *stdin_bytes;
Packit ae235b
  size_t stdin_buf_len = 0;
Packit ae235b
Packit ae235b
  g_return_if_fail (G_IS_SUBPROCESS (subprocess));
Packit ae235b
  g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
Packit ae235b
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
Packit ae235b
Packit ae235b
  if (stdin_buf != NULL)
Packit ae235b
    stdin_buf_len = strlen (stdin_buf);
Packit ae235b
  stdin_bytes = g_bytes_new (stdin_buf, stdin_buf_len);
Packit ae235b
Packit ae235b
  g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
Packit ae235b
Packit ae235b
  g_bytes_unref (stdin_bytes);
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
communicate_result_validate_utf8 (const char            *stream_name,
Packit ae235b
                                  char                 **return_location,
Packit ae235b
                                  GMemoryOutputStream   *buffer,
Packit ae235b
                                  GError               **error)
Packit ae235b
{
Packit ae235b
  if (return_location == NULL)
Packit ae235b
    return TRUE;
Packit ae235b
Packit ae235b
  if (buffer)
Packit ae235b
    {
Packit ae235b
      const char *end;
Packit ae235b
      *return_location = g_memory_output_stream_steal_data (buffer);
Packit ae235b
      if (!g_utf8_validate (*return_location, -1, &end))
Packit ae235b
        {
Packit ae235b
          g_free (*return_location);
Packit ae235b
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
Packit ae235b
                       "Invalid UTF-8 in child %s at offset %lu",
Packit ae235b
                       stream_name,
Packit ae235b
                       (unsigned long) (end - *return_location));
Packit ae235b
          return FALSE;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    *return_location = NULL;
Packit ae235b
Packit ae235b
  return TRUE;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_subprocess_communicate_utf8_finish:
Packit ae235b
 * @subprocess: Self
Packit ae235b
 * @result: Result
Packit ae235b
 * @stdout_buf: (out) (nullable) (optional) (transfer full): Return location for stdout data
Packit ae235b
 * @stderr_buf: (out) (nullable) (optional) (transfer full): Return location for stderr data
Packit ae235b
 * @error: Error
Packit ae235b
 *
Packit ae235b
 * Complete an invocation of g_subprocess_communicate_utf8_async().
Packit ae235b
 */
Packit ae235b
gboolean
Packit ae235b
g_subprocess_communicate_utf8_finish (GSubprocess   *subprocess,
Packit ae235b
                                      GAsyncResult  *result,
Packit ae235b
                                      char         **stdout_buf,
Packit ae235b
                                      char         **stderr_buf,
Packit ae235b
                                      GError       **error)
Packit ae235b
{
Packit ae235b
  gboolean ret = FALSE;
Packit ae235b
  CommunicateState *state;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
Packit ae235b
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
Packit ae235b
Packit ae235b
  g_object_ref (result);
Packit ae235b
Packit ae235b
  state = g_task_get_task_data ((GTask*)result);
Packit ae235b
  if (!g_task_propagate_boolean ((GTask*)result, error))
Packit ae235b
    goto out;
Packit ae235b
Packit ae235b
  /* TODO - validate UTF-8 while streaming, rather than all at once.
Packit ae235b
   */
Packit ae235b
  if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
Packit ae235b
                                         state->stdout_buf,
Packit ae235b
                                         error))
Packit ae235b
    goto out;
Packit ae235b
  if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
Packit ae235b
                                         state->stderr_buf,
Packit ae235b
                                         error))
Packit ae235b
    goto out;
Packit ae235b
Packit ae235b
  ret = TRUE;
Packit ae235b
 out:
Packit ae235b
  g_object_unref (result);
Packit ae235b
  return ret;
Packit ae235b
}