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