1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2012 Red Hat, Inc.
4 * Copyright © 2012-2013 Canonical Limited
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; either version 2 of the licence or (at
9 * your option) any later version.
11 * See the included COPYING file for more information.
13 * Authors: Colin Walters <walters@verbum.org>
14 * Ryan Lortie <desrt@desrt.ca>
20 * @short_description: Child processes
21 * @see_also: #GSubprocessLauncher
23 * #GSubprocess allows the creation of and interaction with child
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
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.
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.
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.
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
56 * #GSubprocess will quickly reap all child processes as they exit,
57 * avoiding "zombie processes" remaining around for long periods of
58 * time. g_subprocess_wait() can be used to wait for this to happen,
59 * but it will happen even without the call being explicitly made.
61 * As a matter of principle, #GSubprocess has no API that accepts
62 * shell-style space-separated strings. It will, however, match the
63 * typical shell behaviour of searching the PATH for executables that do
64 * not contain a directory separator in their name.
66 * #GSubprocess attempts to have a very simple API for most uses (ie:
67 * spawning a subprocess with arguments and support for most typical
68 * kinds of input and output redirection). See g_subprocess_new(). The
69 * #GSubprocessLauncher API is provided for more complicated cases
70 * (advanced types of redirection, environment variable manipulation,
71 * change of working directory, child setup functions, etc).
73 * A typical use of #GSubprocess will involve calling
74 * g_subprocess_new(), followed by g_subprocess_wait() 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).
84 #include "gsubprocess.h"
85 #include "gsubprocesslauncher-private.h"
86 #include "gasyncresult.h"
87 #include "giostream.h"
88 #include "gmemoryinputstream.h"
90 #include "glib-private.h"
94 #include <gio/gunixoutputstream.h>
95 #include <gio/gfiledescriptorbased.h>
96 #include <gio/gunixinputstream.h>
98 #include <glib-unix.h>
102 #define _WIN32_WINNT 0x0500
104 #include "giowin32-priv.h"
111 #define COMMUNICATE_READ_SIZE 4096
113 /* A GSubprocess can have two possible states: running and not.
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.
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.
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())
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.
137 static void initable_iface_init (GInitableIface *initable_iface);
139 typedef GObjectClass GSubprocessClass;
145 /* only used during construction */
146 GSubprocessLauncher *launcher;
147 GSubprocessFlags flags;
150 /* state tracking variables */
151 gchar identifier[24];
156 GMutex pending_waits_lock;
157 GSList *pending_waits;
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;
165 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
166 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init));
179 GSpawnChildSetupFunc child_setup_func;
180 gpointer child_setup_data;
181 GArray *basic_fd_assignments;
182 GArray *needdup_fd_assignments;
186 unset_cloexec (int fd)
191 flags = fcntl (fd, F_GETFD, 0);
195 flags &= (~FD_CLOEXEC);
197 result = fcntl (fd, F_SETFD, flags);
198 while (result == -1 && errno == EINTR);
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.
208 child_setup (gpointer user_data)
210 ChildData *child_data = user_data;
214 /* We're on the child side now. "Rename" the file descriptors in
215 * child_data.fds[] to stdin/stdout/stderr.
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.
221 for (i = 0; i < 3; i++)
222 if (child_data->fds[i] != -1 && child_data->fds[i] != i)
225 result = dup2 (child_data->fds[i], i);
226 while (result == -1 && errno == EINTR);
229 /* Basic fd assignments we can just unset FD_CLOEXEC */
230 if (child_data->basic_fd_assignments)
232 for (i = 0; i < child_data->basic_fd_assignments->len; i++)
234 gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
240 /* If we're doing remapping fd assignments, we need to handle
241 * the case where the user has specified e.g.:
244 * We do this by duping the source fds temporarily.
246 if (child_data->needdup_fd_assignments)
248 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
250 gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
254 new_parent_fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
255 while (parent_fd == -1 && errno == EINTR);
257 g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
259 for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
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);
264 if (parent_fd == child_fd)
266 unset_cloexec (parent_fd);
271 result = dup2 (parent_fd, child_fd);
272 while (result == -1 && errno == EINTR);
273 (void) close (parent_fd);
278 if (child_data->child_setup_func)
279 child_data->child_setup_func (child_data->child_setup_data);
282 static GInputStream *
283 platform_input_stream_from_spawn_fd (gint fd)
289 return g_unix_input_stream_new (fd, TRUE);
291 return g_win32_input_stream_new_from_fd (fd, TRUE);
295 static GOutputStream *
296 platform_output_stream_from_spawn_fd (gint fd)
302 return g_unix_output_stream_new (fd, TRUE);
304 return g_win32_output_stream_new_from_fd (fd, TRUE);
310 unix_open_file (const char *filename,
316 my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
318 /* If we return -1 we should also set the error */
321 gint saved_errno = errno;
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... */
337 g_subprocess_set_property (GObject *object,
342 GSubprocess *self = G_SUBPROCESS (object);
347 self->flags = g_value_get_flags (value);
351 self->argv = g_value_dup_boxed (value);
355 g_assert_not_reached ();
360 g_subprocess_exited (GPid pid,
364 GSubprocess *self = user_data;
367 g_assert (self->pid == pid);
369 g_mutex_lock (&self->pending_waits_lock);
370 self->status = status;
371 tasks = self->pending_waits;
372 self->pending_waits = NULL;
374 g_mutex_unlock (&self->pending_waits_lock);
376 /* Signal anyone in g_subprocess_wait_async() to wake up now */
379 g_task_return_boolean (tasks->data, TRUE);
380 tasks = g_slist_delete_link (tasks, tasks);
383 g_spawn_close_pid (pid);
389 initable_init (GInitable *initable,
390 GCancellable *cancellable,
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;
402 /* this is a programmer error */
403 if (!self->argv || !self->argv[0] || !self->argv[0][0])
406 if (g_cancellable_set_error_if_cancelled (cancellable, error))
409 /* We must setup the three fds that will end up in the child as stdin,
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];
419 else if (self->launcher)
421 if (self->launcher->stdin_fd != -1)
422 child_data.fds[0] = self->launcher->stdin_fd;
423 else if (self->launcher->stdin_path != NULL)
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)
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];
438 else if (self->launcher)
440 if (self->launcher->stdout_fd != -1)
441 child_data.fds[1] = self->launcher->stdout_fd;
442 else if (self->launcher->stdout_path != NULL)
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)
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;
460 else if (self->launcher)
462 if (self->launcher->stderr_fd != -1)
463 child_data.fds[2] = self->launcher->stderr_fd;
464 else if (self->launcher->stderr_path != NULL)
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)
476 child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
477 child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
481 /* argv0 has no '/' in it? We better do a PATH lookup. */
482 if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
484 if (self->launcher && self->launcher->path_from_envp)
485 spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
487 spawn_flags |= G_SPAWN_SEARCH_PATH;
490 if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
491 spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
493 spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
494 spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
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,
500 self->launcher ? self->launcher->envp : NULL,
502 child_setup, &child_data,
504 pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
506 g_assert (success == (self->pid != 0));
513 identifier = (guint64) GetProcessId (self->pid);
515 identifier = (guint64) self->pid;
518 s = snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
519 g_assert (0 < s && s < sizeof self->identifier);
522 /* Start attempting to reap the child immediately */
525 GMainContext *worker_context;
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);
536 /* we don't need this past init... */
537 self->launcher = NULL;
539 for (i = 0; i < 3; i++)
540 if (close_fds[i] != -1)
541 close (close_fds[i]);
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]);
551 g_subprocess_finalize (GObject *object)
553 GSubprocess *self = G_SUBPROCESS (object);
555 g_assert (self->pending_waits == NULL);
556 g_assert (self->pid == 0);
558 g_clear_object (&self->stdin_pipe);
559 g_clear_object (&self->stdout_pipe);
560 g_clear_object (&self->stderr_pipe);
563 G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
567 g_subprocess_init (GSubprocess *self)
572 initable_iface_init (GInitableIface *initable_iface)
574 initable_iface->init = initable_init;
578 g_subprocess_class_init (GSubprocessClass *class)
580 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
582 gobject_class->finalize = g_subprocess_finalize;
583 gobject_class->set_property = g_subprocess_set_property;
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));
596 * g_subprocess_new: (skip)
598 * Create a new process with the given flags and varargs argument list.
600 * The argument list must be terminated with %NULL.
602 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
608 g_subprocess_new (GSubprocessFlags flags,
618 g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
619 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
621 args = g_ptr_array_new ();
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);
629 result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
631 g_ptr_array_free (args, TRUE);
639 * Create a new process with the given flags and argument list.
641 * The argument list is expected to be %NULL-terminated.
643 * Returns: A newly created #GSubprocess, or %NULL on error (and @error
647 * Rename to: g_subprocess_new
650 g_subprocess_newv (const gchar * const *argv,
651 GSubprocessFlags flags,
654 g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
656 return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
663 g_subprocess_get_identifier (GSubprocess *self)
665 g_return_val_if_fail (G_IS_SUBPROCESS (self), NULL);
668 return self->identifier;
674 g_subprocess_get_stdin_pipe (GSubprocess *self)
676 g_return_val_if_fail (G_IS_SUBPROCESS (self), NULL);
677 g_return_val_if_fail (self->stdin_pipe, NULL);
679 return self->stdin_pipe;
683 g_subprocess_get_stdout_pipe (GSubprocess *self)
685 g_return_val_if_fail (G_IS_SUBPROCESS (self), NULL);
686 g_return_val_if_fail (self->stdout_pipe, NULL);
688 return self->stdout_pipe;
692 g_subprocess_get_stderr_pipe (GSubprocess *self)
694 g_return_val_if_fail (G_IS_SUBPROCESS (self), NULL);
695 g_return_val_if_fail (self->stderr_pipe, NULL);
697 return self->stderr_pipe;
701 g_subprocess_wait_cancelled (GCancellable *cancellable,
704 GTask *task = user_data;
707 self = g_task_get_source_object (task);
709 g_mutex_lock (&self->pending_waits_lock);
710 self->pending_waits = g_slist_remove (self->pending_waits, task);
711 g_mutex_unlock (&self->pending_waits_lock);
713 g_task_return_boolean (task, FALSE);
714 g_object_unref (task);
718 g_subprocess_wait_async (GSubprocess *self,
719 GCancellable *cancellable,
720 GAsyncReadyCallback callback,
725 task = g_task_new (self, cancellable, callback, user_data);
727 g_mutex_lock (&self->pending_waits_lock);
730 /* Only bother with cancellable if we're putting it in the list.
731 * If not, it's going to dispatch immediately anyway and we will
732 * see the cancellation in the _finish().
735 g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
737 self->pending_waits = g_slist_prepend (self->pending_waits, task);
740 g_mutex_unlock (&self->pending_waits_lock);
742 /* If we still have task then it's because did_exit is already TRUE */
745 g_task_return_boolean (task, TRUE);
746 g_object_unref (task);
751 g_subprocess_wait_finish (GSubprocess *self,
752 GAsyncResult *result,
755 return g_task_propagate_boolean (G_TASK (result), error);
758 /* Some generic helpers for emulating synchronous operations using async
762 g_subprocess_sync_setup (void)
764 g_main_context_push_thread_default (g_main_context_new ());
768 g_subprocess_sync_done (GObject *source_object,
769 GAsyncResult *result,
772 GAsyncResult **result_ptr = user_data;
774 *result_ptr = g_object_ref (result);
778 g_subprocess_sync_complete (GAsyncResult **result)
780 GMainContext *context = g_main_context_get_thread_default ();
783 g_main_context_iteration (context, TRUE);
785 g_main_context_pop_thread_default (context);
786 g_main_context_unref (context);
791 * @self: a #GSubprocess
792 * @cancellable: a #GCancellable
795 * Synchronously wait for the subprocess to terminate, returning the
796 * status code in @out_exit_status. See the documentation of
797 * g_spawn_check_exit_status() for how to interpret it. Note that if
798 * @error is set, then @out_exit_status will be left uninitialized.
800 * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
805 g_subprocess_wait (GSubprocess *self,
806 GCancellable *cancellable,
809 GAsyncResult *result = NULL;
812 g_return_val_if_fail (G_IS_SUBPROCESS (self), FALSE);
814 /* Synchronous waits are actually the 'more difficult' case because we
815 * need to deal with the possibility of cancellation. That more or
816 * less implies that we need a main context (to dispatch either of the
817 * possible reasons for the operation ending).
819 * So we make one and then do this async...
822 if (g_cancellable_set_error_if_cancelled (cancellable, error))
825 /* We can shortcut in the case that the process already quit (but only
826 * after we checked the cancellable).
831 /* Otherwise, we need to do this the long way... */
832 g_subprocess_sync_setup ();
833 g_subprocess_wait_async (self, cancellable, g_subprocess_sync_done, &result);
834 g_subprocess_sync_complete (&result);
835 success = g_subprocess_wait_finish (self, result, error);
836 g_object_unref (result);
842 * g_subprocess_wait_sync_check:
843 * @self: a #GSubprocess
844 * @cancellable: a #GCancellable
847 * Combines g_subprocess_wait_sync() with g_spawn_check_exit_status().
849 * Returns: %TRUE on success, %FALSE if process exited abnormally, or @cancellable was cancelled
854 g_subprocess_wait_check (GSubprocess *self,
855 GCancellable *cancellable,
858 return g_subprocess_wait (self, cancellable, error) &&
859 g_spawn_check_exit_status (self->status, error);
863 g_subprocess_wait_check_async (GSubprocess *self,
864 GCancellable *cancellable,
865 GAsyncReadyCallback callback,
868 g_subprocess_wait_async (self, cancellable, callback, user_data);
872 g_subprocess_wait_check_finish (GSubprocess *self,
873 GAsyncResult *result,
876 return g_subprocess_wait_finish (self, result, error) &&
877 g_spawn_check_exit_status (self->status, error);
883 GSubprocess *subprocess;
888 g_subprocess_actually_send_signal (gpointer user_data)
890 SignalRecord *signal_record = user_data;
892 /* The pid is set to zero from the worker thread as well, so we don't
893 * need to take a lock in order to prevent it from changing under us.
895 if (signal_record->subprocess->pid)
896 kill (signal_record->subprocess->pid, signal_record->signalnum);
898 g_object_unref (signal_record->subprocess);
900 g_slice_free (SignalRecord, signal_record);
906 g_subprocess_dispatch_signal (GSubprocess *self,
909 SignalRecord signal_record = { g_object_ref (self), signalnum };
911 g_return_if_fail (G_IS_SUBPROCESS (self));
913 /* This MUST be a lower priority than the priority that the child
914 * watch source uses in initable_init().
916 * Reaping processes, reporting the results back to GSubprocess and
917 * sending signals is all done in the glib worker thread. We cannot
918 * have a kill() done after the reap and before the report without
919 * risking killing a process that's no longer there so the kill()
920 * needs to have the lower priority.
922 * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
924 g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
925 G_PRIORITY_HIGH_IDLE,
926 g_subprocess_actually_send_signal,
927 g_slice_dup (SignalRecord, &signal_record),
932 * g_subprocess_send_signal:
933 * @self: a #GSubprocess
934 * @signal_num: the signal number to send
936 * Sends the UNIX signal @signal_num to the subprocess, if it is still
939 * This API is race-free. If the subprocess has terminated, it will not
942 * This API is not available on Windows.
947 g_subprocess_send_signal (GSubprocess *self,
950 g_return_if_fail (G_IS_SUBPROCESS (self));
952 g_subprocess_dispatch_signal (self, signal_num);
957 * g_subprocess_force_exit:
958 * @self: a #GSubprocess
960 * Use an operating-system specific method to attempt an immediate,
961 * forceful termination of the process. There is no mechanism to
962 * determine whether or not the request itself was successful;
963 * however, you can use g_subprocess_wait() to monitor the status of
964 * the process after calling this function.
966 * On Unix, this function sends %SIGKILL.
971 g_subprocess_force_exit (GSubprocess *self)
973 g_return_if_fail (G_IS_SUBPROCESS (self));
976 g_subprocess_dispatch_signal (self, SIGKILL);
978 TerminateProcess (self->pid, 1);
983 * g_subprocess_get_status:
984 * @self: a #GSubprocess
986 * Gets the raw status code of the process, as from waitpid().
988 * This value has no particular meaning, but it can be used with the
989 * macros defined by the system headers such as WIFEXITED. It can also
990 * be used with g_spawn_check_exit_status().
992 * It is more likely that you want to use g_subprocess_get_if_exited()
993 * followed by g_subprocess_get_exit_status().
995 * It is an error to call this function before g_subprocess_wait() has
998 * Returns: the (meaningless) waitpid() exit status from the kernel
1003 g_subprocess_get_status (GSubprocess *self)
1005 g_return_val_if_fail (G_IS_SUBPROCESS (self), FALSE);
1006 g_return_val_if_fail (self->pid == 0, FALSE);
1008 return self->status;
1012 * g_subprocess_get_successful:
1013 * @self: a #GSubprocess
1015 * Checks if the process was "successful". A process is considered
1016 * successful if it exited cleanly with an exit status of 0, either by
1017 * way of the exit() system call or return from main().
1019 * It is an error to call this function before g_subprocess_wait() has
1022 * Returns: %TRUE if the process exited cleanly with a exit status of 0
1027 g_subprocess_get_successful (GSubprocess *self)
1029 g_return_val_if_fail (G_IS_SUBPROCESS (self), FALSE);
1030 g_return_val_if_fail (self->pid == 0, FALSE);
1032 return WIFEXITED (self->status) && WEXITSTATUS (self->status) == 0;
1036 * g_subprocess_get_if_exited:
1037 * @self: a #GSubprocess
1039 * Check if the given subprocess exited normally (ie: by way of exit()
1040 * or return from main()).
1042 * This is equivalent to the system WIFEXITED macro.
1044 * It is an error to call this function before g_subprocess_wait() has
1047 * Returns: %TRUE if the case of a normal exit
1052 g_subprocess_get_if_exited (GSubprocess *self)
1054 g_return_val_if_fail (G_IS_SUBPROCESS (self), FALSE);
1055 g_return_val_if_fail (self->pid == 0, FALSE);
1057 return WIFEXITED (self->status);
1061 * g_subprocess_get_exit_status:
1062 * @self: a #GSubprocess
1064 * Check the exit status of the subprocess, given that it exited
1065 * normally. This is the value passed to the exit() system call or the
1066 * return value from main.
1068 * This is equivalent to the system WEXITSTATUS macro.
1070 * It is an error to call this function before g_subprocess_wait() and
1071 * unless g_subprocess_get_if_exited() returned %TRUE.
1073 * Returns: the exit status
1078 g_subprocess_get_exit_status (GSubprocess *self)
1080 g_return_val_if_fail (G_IS_SUBPROCESS (self), 1);
1081 g_return_val_if_fail (self->pid == 0, 1);
1082 g_return_val_if_fail (WIFEXITED (self->status), 1);
1084 return WEXITSTATUS (self->status);
1088 * g_subprocess_get_if_signaled:
1089 * @self: a #GSubprocess
1091 * Check if the given subprocess terminated in response to a signal.
1093 * This is equivalent to the system WIFSIGNALED macro.
1095 * It is an error to call this function before g_subprocess_wait() has
1098 * Returns: %TRUE if the case of termination due to a signal
1103 g_subprocess_get_if_signaled (GSubprocess *self)
1105 g_return_val_if_fail (G_IS_SUBPROCESS (self), FALSE);
1106 g_return_val_if_fail (self->pid == 0, FALSE);
1108 return WIFSIGNALED (self->status);
1112 * g_subprocess_get_term_sig:
1113 * @self: a #GSubprocess
1115 * Get the signal number that caused the subprocess to terminate, given
1116 * that it terminated due to a signal.
1118 * This is equivalent to the system WTERMSIG macro.
1120 * It is an error to call this function before g_subprocess_wait() and
1121 * unless g_subprocess_get_if_signaled() returned %TRUE.
1123 * Returns: the signal causing termination
1128 g_subprocess_get_term_sig (GSubprocess *self)
1130 g_return_val_if_fail (G_IS_SUBPROCESS (self), 0);
1131 g_return_val_if_fail (self->pid == 0, 0);
1132 g_return_val_if_fail (WIFSIGNALED (self->status), 0);
1134 return WTERMSIG (self->status);
1139 g_subprocess_set_launcher (GSubprocess *subprocess,
1140 GSubprocessLauncher *launcher)
1142 subprocess->launcher = launcher;
1146 /* g_subprocess_communicate implementation below:
1148 * This is a tough problem. We have to watch 5 things at the same time:
1150 * - writing to stdin made progress
1151 * - reading from stdout made progress
1152 * - reading from stderr made progress
1153 * - process terminated
1154 * - cancellable being cancelled by caller
1156 * We use a GMainContext for all of these (either as async function
1157 * calls or as a GSource (in the case of the cancellable). That way at
1158 * least we don't have to worry about threading.
1160 * For the sync case we use the usual trick of creating a private main
1161 * context and iterating it until completion.
1163 * It's very possible that the process will dump a lot of data to stdout
1164 * just before it quits, so we can easily have data to read from stdout
1165 * and see the process has terminated at the same time. We want to make
1166 * sure that we read all of the data from the pipes first, though, so we
1167 * do IO operations at a higher priority than the wait operation (which
1168 * is at G_IO_PRIORITY_DEFAULT). Even in the case that we have to do
1169 * multiple reads to get this data, the pipe() will always be polling
1170 * as ready and with the async result for the read at a higher priority,
1171 * the main context will not dispatch the completion for the wait().
1173 * We keep our own private GCancellable. In the event that any of the
1174 * above suffers from an error condition (including the user cancelling
1175 * their cancellable) we immediately dispatch the GTask with the error
1176 * result and fire our cancellable to cleanup any pending operations.
1177 * In the case that the error is that the user's cancellable was fired,
1178 * it's vaguely wasteful to report an error because GTask will handle
1179 * this automatically, so we just return FALSE.
1181 * We let each pending sub-operation take a ref on the GTask of the
1182 * communicate operation. We have to be careful that we don't report
1183 * the task completion more than once, though, so we keep a flag for
1188 const gchar *stdin_data;
1192 /* Not actually GString. Just borrowing the struct. */
1193 GString stdout_string;
1194 GString stderr_string;
1196 GBytes *unref_this_later;
1197 gchar *free_this_later;
1199 GCancellable *cancellable;
1200 GSource *cancellable_source;
1202 gboolean completion_reported;
1206 ensure_string_allocated (GString *str)
1208 /* This will work because the first time we will set it to
1209 * COMMUNICATE_READ_SIZE and then all future attempts will grow by at
1210 * least that much (as a result of multiplying the existing value by
1213 if (str->len + COMMUNICATE_READ_SIZE > str->allocated_len)
1215 str->allocated_len = MAX(COMMUNICATE_READ_SIZE, str->allocated_len * 2);
1216 str->str = g_realloc (str->str, str->allocated_len);
1221 g_subprocess_communicate_made_progress (GObject *source_object,
1222 GAsyncResult *result,
1225 CommunicateState *state;
1226 GSubprocess *subprocess;
1227 GError *error = NULL;
1231 g_assert (source_object != NULL);
1234 subprocess = g_task_get_source_object (task);
1235 state = g_task_get_task_data (task);
1236 source = source_object;
1238 if (source == subprocess->stdin_pipe)
1242 s = g_output_stream_write_finish (subprocess->stdin_pipe, result, &error);
1247 g_assert (0 < s && s < state->stdin_length);
1248 g_assert (state->stdin_offset + s <= state->stdin_length);
1249 state->stdin_offset += s;
1251 if (state->stdin_offset != state->stdin_length)
1254 g_output_stream_write_async (subprocess->stdin_pipe,
1255 state->stdin_data + state->stdin_offset,
1256 state->stdin_length - state->stdin_offset,
1259 g_subprocess_communicate_made_progress,
1265 else if (source == subprocess->stdout_pipe)
1269 s = g_input_stream_read_finish (subprocess->stdout_pipe, result, &error);
1270 g_assert (s <= COMMUNICATE_READ_SIZE);
1272 /* If s is 0 then we have EOF and should not read more, but should
1273 * continue to try the other event sources.
1275 * If s is -1 then error will be set and we deal with that below.
1277 * Only have to handle the result > 0 case.
1281 state->stdout_string.len += s;
1283 ensure_string_allocated (&state->stdout_string);
1285 g_input_stream_read_async (subprocess->stdout_pipe, state->stdout_string.str + state->stdout_string.len,
1286 COMMUNICATE_READ_SIZE, G_PRIORITY_DEFAULT - 1, state->cancellable,
1287 g_subprocess_communicate_made_progress, g_object_ref (task));
1291 else if (source == subprocess->stderr_pipe)
1295 s = g_input_stream_read_finish (subprocess->stdout_pipe, result, &error);
1296 g_assert (s <= COMMUNICATE_READ_SIZE);
1301 state->stderr_string.len += s;
1303 ensure_string_allocated (&state->stderr_string);
1305 g_input_stream_read_async (subprocess->stderr_pipe, state->stderr_string.str + state->stderr_string.len,
1306 COMMUNICATE_READ_SIZE, G_PRIORITY_DEFAULT - 1, state->cancellable,
1307 g_subprocess_communicate_made_progress, g_object_ref (task));
1311 else if (source == subprocess)
1313 if (g_subprocess_wait_finish (subprocess, result, &error))
1315 /* It is not possible that we had a successful completion if
1316 * the task was already completed because we flag our own
1317 * cancellable in that case.
1319 g_assert (!state->completion_reported);
1320 state->completion_reported = TRUE;
1321 g_task_return_boolean (task, TRUE);
1325 g_assert_not_reached ();
1329 /* Only report the first error we see.
1331 * We might be seeing an error as a result of the cancellation
1332 * done when the process quits.
1334 if (!state->completion_reported)
1336 state->completion_reported = TRUE;
1338 g_cancellable_cancel (state->cancellable);
1339 g_task_return_error (task, error);
1342 g_error_free (error);
1345 g_object_unref (task);
1349 g_subprocess_communicate_cancelled (gpointer user_data)
1351 CommunicateState *state = user_data;
1353 g_cancellable_cancel (state->cancellable);
1359 g_subprocess_communicate_state_free (gpointer data)
1361 CommunicateState *state = data;
1363 g_free (state->stdout_string.str);
1364 g_free (state->stderr_string.str);
1365 g_free (state->free_this_later);
1367 if (!g_source_is_destroyed (state->cancellable_source))
1368 g_source_destroy (state->cancellable_source);
1369 g_source_unref (state->cancellable_source);
1371 if (state->unref_this_later)
1372 g_bytes_unref (state->unref_this_later);
1374 g_slice_free (CommunicateState, state);
1377 static CommunicateState *
1378 g_subprocess_communicate_internal (GSubprocess *subprocess,
1379 GBytes *stdin_bytes,
1380 const gchar *stdin_data,
1381 gssize stdin_length,
1382 GCancellable *cancellable,
1383 GAsyncReadyCallback callback,
1386 CommunicateState *state;
1389 task = g_task_new (subprocess, cancellable, callback, user_data);
1390 state = g_slice_new0 (CommunicateState);
1391 g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1395 g_assert (!stdin_data && !stdin_length && (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1396 state->stdin_data = g_bytes_get_data (stdin_bytes, &state->stdin_length);
1397 state->unref_this_later = g_bytes_ref (stdin_bytes);
1399 else if (stdin_data)
1401 g_assert (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE);
1402 if (stdin_length < 0)
1403 state->stdin_length = strlen (stdin_data);
1405 state->stdin_length = stdin_length;
1407 state->free_this_later = g_memdup (stdin_data, state->stdin_length);
1408 state->stdin_data = state->free_this_later;
1411 state->cancellable = g_cancellable_new ();
1415 state->cancellable_source = g_cancellable_source_new (cancellable);
1416 /* No ref held here, but we unref the source from state's free function */
1417 g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1418 g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1421 if (subprocess->stdin_pipe && state->stdin_length)
1422 g_output_stream_write_async (subprocess->stdin_pipe, state->stdin_data, state->stdin_length, G_PRIORITY_DEFAULT,
1423 state->cancellable, g_subprocess_communicate_made_progress, g_object_ref (task));
1425 if (subprocess->stdout_pipe)
1427 ensure_string_allocated (&state->stdout_string);
1429 g_input_stream_read_async (subprocess->stdout_pipe, state->stdout_string.str, COMMUNICATE_READ_SIZE,
1430 G_PRIORITY_DEFAULT - 1, state->cancellable,
1431 g_subprocess_communicate_made_progress, g_object_ref (task));
1434 if (subprocess->stderr_pipe)
1436 ensure_string_allocated (&state->stderr_string);
1438 g_input_stream_read_async (subprocess->stderr_pipe, state->stderr_string.str, COMMUNICATE_READ_SIZE,
1439 G_PRIORITY_DEFAULT - 1, state->cancellable,
1440 g_subprocess_communicate_made_progress, g_object_ref (task));
1443 g_subprocess_wait_async (subprocess, state->cancellable,
1444 g_subprocess_communicate_made_progress, g_object_ref (task));
1450 * g_Subprocess_communicate:
1451 * @self: a #GSubprocess
1452 * @stdin_data: data to send to the stdin of the subprocess, or %NULL
1453 * @stdin_length: the length of @stdin_data, or -1
1454 * @cancellable: a #GCancellable
1455 * @stdout_data: (out): data read from the subprocess stdout
1456 * @stdout_length: (out): the length of @stdout_data returned
1457 * @stderr_data: (out): data read from the subprocess stderr
1458 * @stderr_length: (out): the length of @stderr_data returned
1459 * @error: a pointer to a %NULL #GError pointer, or %NULL
1461 * Communicate with the subprocess until it terminates.
1463 * If @stdin_data is given, the subprocess must have been created with
1464 * %G_SUBPROCESS_FLAGS_STDIN_PIPE. The given data is fed to the
1465 * stdin of the subprocess and the pipe is closed (ie: EOF).
1467 * At the same time (as not to cause blocking when dealing with large
1468 * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1469 * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those streams.
1470 * The data that was read is returned in @stdout_data and/or
1473 * @stdin_length specifies the length of @stdin_data. If it is -1 then
1474 * @stdin_data is taken to be a nul-terminated string. If the
1475 * subprocess was not created with %G_SUBPROCESS_FLAGS_STDIN_PIPE then
1476 * you must pass %NULL for @stdin_data and 0 for @stdin_length.
1478 * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1479 * @stdout_data will contain the data read from stdout, plus a
1480 * terminating nul character; it will always be non-%NULL (ie:
1481 * containing at least the nul). @stdout_length will be the length of
1482 * the data, excluding the added nul. For subprocesses not created with
1483 * %G_SUBPROCESS_FLAGS_STDOUT_PIPE, @stdout_data will be set to %NULL
1484 * and @stdout_length will be set to zero. stderr is handled in the
1487 * As usual, any output variable may be given as %NULL to ignore it.
1489 * If you desire the stdout and stderr data to be interleaved, create
1490 * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1491 * %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned
1492 * in @stdout_data and @stderr_data will be set to %NULL.
1494 * In case of any error (including cancellation), %FALSE will be
1495 * returned with @error set. Some or all of the stdin data may have
1496 * been written. Any stdout or stderr data that has been read will be
1497 * discarded. None of the out variables (aside from @error) will have
1498 * been set to anything in particular and should not be inspected.
1500 * In the case that %TRUE is returned, the subprocess has exited and the
1501 * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1502 * g_subprocess_get_exit_status()) may be used.
1504 * You should not attempt to use any of the subprocess pipes after
1505 * starting this function, since they may be left in strange states,
1506 * even if the operation was cancelled. You should especially not
1507 * attempt to interact with the pipes while the operation is in progress
1508 * (either from another thread or if using the asynchronous version).
1510 * Returns: %TRUE if successful
1515 g_subprocess_communicate (GSubprocess *subprocess,
1516 const gchar *stdin_data,
1517 gssize stdin_length,
1518 GCancellable *cancellable,
1519 gchar **stdout_data,
1520 gsize *stdout_length,
1521 gchar **stderr_data,
1522 gsize *stderr_length,
1525 GAsyncResult *result = NULL;
1528 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1529 g_return_val_if_fail (stdin_length == 0 || stdin_data != NULL, FALSE);
1530 g_return_val_if_fail (stdin_data == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1531 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1532 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1534 g_subprocess_sync_setup ();
1535 g_subprocess_communicate_internal (subprocess, NULL, stdin_data, stdin_length,
1536 cancellable, g_subprocess_sync_done, &result);
1537 g_subprocess_sync_complete (&result);
1538 success = g_subprocess_communicate_finish (subprocess, result,
1539 stdout_data, stdout_length,
1540 stderr_data, stderr_length, error);
1541 g_object_unref (result);
1547 g_subprocess_communicate_async (GSubprocess *subprocess,
1548 const gchar *stdin_data,
1549 gssize stdin_length,
1550 GCancellable *cancellable,
1551 GAsyncReadyCallback callback,
1554 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1555 g_return_if_fail (stdin_length == 0 || stdin_data != NULL);
1556 g_return_if_fail (stdin_data == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1557 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1559 g_subprocess_communicate_internal (subprocess, NULL, stdin_data, stdin_length, cancellable, callback, user_data);
1563 g_subprocess_communicate_finish (GSubprocess *subprocess,
1564 GAsyncResult *result,
1565 gchar **stdout_data,
1566 gsize *stdout_length,
1567 gchar **stderr_data,
1568 gsize *stderr_length,
1571 CommunicateState *state;
1575 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1576 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1577 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1579 task = G_TASK (result);
1580 state = g_task_get_task_data (task);
1582 success = g_task_propagate_boolean (task, error);
1590 string = g_realloc (state->stdout_string.str, state->stdout_string.len + 1);
1591 string[state->stdout_string.len] = '\0';
1592 state->stdout_string.str = NULL;
1593 *stdout_data = string;
1597 *stdout_length = state->stdout_string.len;
1603 string = g_realloc (state->stderr_string.str, state->stderr_string.len + 1);
1604 string[state->stderr_string.len] = '\0';
1605 state->stderr_string.str = NULL;
1606 *stderr_data = string;
1610 *stderr_length = state->stderr_string.len;
1617 g_subprocess_communicate_bytes (GSubprocess *subprocess,
1618 GBytes *stdin_bytes,
1619 GCancellable *cancellable,
1620 GBytes **stdout_bytes,
1621 GBytes **stderr_bytes,
1624 GAsyncResult *result = NULL;
1627 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1628 g_return_val_if_fail (stdin_bytes == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1629 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1630 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1632 g_subprocess_sync_setup ();
1633 g_subprocess_communicate_internal (subprocess, stdin_bytes, NULL, 0, cancellable, g_subprocess_sync_done, &result);
1634 g_subprocess_sync_complete (&result);
1635 success = g_subprocess_communicate_bytes_finish (subprocess, result, stdout_bytes, stderr_bytes, error);
1636 g_object_unref (result);
1642 g_subprocess_communicate_bytes_async (GSubprocess *subprocess,
1643 GBytes *stdin_bytes,
1644 GCancellable *cancellable,
1645 GAsyncReadyCallback callback,
1648 g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1649 g_return_if_fail (stdin_bytes == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1650 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1652 g_subprocess_communicate_internal (subprocess, stdin_bytes, NULL, 0, cancellable, callback, user_data);
1656 g_subprocess_communicate_bytes_finish (GSubprocess *subprocess,
1657 GAsyncResult *result,
1658 GBytes **stdout_bytes,
1659 GBytes **stderr_bytes,
1664 gsize stdout_length;
1666 gsize stderr_length;
1668 g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1669 g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1670 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1672 success = g_subprocess_communicate_finish (subprocess, result,
1673 stdout_bytes ? &stdout_data : NULL,
1674 stdout_bytes ? &stdout_length : NULL,
1675 stderr_bytes ? &stderr_data : NULL,
1676 stderr_bytes ? &stderr_length : NULL,
1682 *stdout_bytes = g_bytes_new_take (stdout_data, stdout_length);
1685 *stderr_bytes = g_bytes_new_take (stderr_data, stderr_length);