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