1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::AsyncResult;
use crate::Cancellable;
use crate::Initable;
use crate::InputStream;
use crate::OutputStream;
use crate::SubprocessFlags;
use glib::object::IsA;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::pin::Pin;
use std::ptr;

glib::wrapper! {
    /// [`Subprocess`][crate::Subprocess] allows the creation of and interaction with child
    /// processes.
    ///
    /// Processes can be communicated with using standard GIO-style APIs (ie:
    /// [`InputStream`][crate::InputStream], [`OutputStream`][crate::OutputStream]). There are GIO-style APIs to wait for
    /// process termination (ie: cancellable and with an asynchronous
    /// variant).
    ///
    /// There is an API to force a process to terminate, as well as a
    /// race-free API for sending UNIX signals to a subprocess.
    ///
    /// One major advantage that GIO brings over the core GLib library is
    /// comprehensive API for asynchronous I/O, such
    /// [`OutputStreamExt::splice_async()`][crate::prelude::OutputStreamExt::splice_async()]. This makes GSubprocess
    /// significantly more powerful and flexible than equivalent APIs in
    /// some other languages such as the `subprocess.py`
    /// included with Python. For example, using [`Subprocess`][crate::Subprocess] one could
    /// create two child processes, reading standard output from the first,
    /// processing it, and writing to the input stream of the second, all
    /// without blocking the main loop.
    ///
    /// A powerful [`communicate()`][Self::communicate()] API is provided similar to the
    /// ``communicate()`` method of `subprocess.py`. This enables very easy
    /// interaction with a subprocess that has been opened with pipes.
    ///
    /// [`Subprocess`][crate::Subprocess] defaults to tight control over the file descriptors open
    /// in the child process, avoiding dangling-fd issues that are caused by
    /// a simple `fork()`/`exec()`. The only open file descriptors in the
    /// spawned process are ones that were explicitly specified by the
    /// [`Subprocess`][crate::Subprocess] API (unless [`SubprocessFlags::INHERIT_FDS`][crate::SubprocessFlags::INHERIT_FDS] was
    /// specified).
    ///
    /// [`Subprocess`][crate::Subprocess] will quickly reap all child processes as they exit,
    /// avoiding "zombie processes" remaining around for long periods of
    /// time. [`wait()`][Self::wait()] can be used to wait for this to happen,
    /// but it will happen even without the call being explicitly made.
    ///
    /// As a matter of principle, [`Subprocess`][crate::Subprocess] has no API that accepts
    /// shell-style space-separated strings. It will, however, match the
    /// typical shell behaviour of searching the PATH for executables that do
    /// not contain a directory separator in their name. By default, the `PATH`
    /// of the current process is used. You can specify
    /// [`SubprocessFlags::SEARCH_PATH_FROM_ENVP`][crate::SubprocessFlags::SEARCH_PATH_FROM_ENVP] to use the `PATH` of the
    /// launcher environment instead.
    ///
    /// [`Subprocess`][crate::Subprocess] attempts to have a very simple API for most uses (ie:
    /// spawning a subprocess with arguments and support for most typical
    /// kinds of input and output redirection). See `g_subprocess_new()`. The
    /// [`SubprocessLauncher`][crate::SubprocessLauncher] API is provided for more complicated cases
    /// (advanced types of redirection, environment variable manipulation,
    /// change of working directory, child setup functions, etc).
    ///
    /// A typical use of [`Subprocess`][crate::Subprocess] will involve calling
    /// `g_subprocess_new()`, followed by [`wait_async()`][Self::wait_async()] or
    /// [`wait()`][Self::wait()]. After the process exits, the status can be
    /// checked using functions such as [`has_exited()`][Self::has_exited()] (which
    /// are similar to the familiar WIFEXITED-style POSIX macros).
    ///
    /// # Implements
    ///
    /// [`trait@glib::ObjectExt`], [`InitableExt`][trait@crate::prelude::InitableExt]
    #[doc(alias = "GSubprocess")]
    pub struct Subprocess(Object<ffi::GSubprocess>) @implements Initable;

    match fn {
        type_ => || ffi::g_subprocess_get_type(),
    }
}

impl Subprocess {
    //#[doc(alias = "g_subprocess_new")]
    //pub fn new(flags: SubprocessFlags, error: Option<&mut glib::Error>, argv0: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) -> Subprocess {
    //    unsafe { TODO: call ffi:g_subprocess_new() }
    //}

    /// Create a new process with the given flags and argument list.
    ///
    /// The argument list is expected to be [`None`]-terminated.
    /// ## `argv`
    /// commandline arguments for the subprocess
    /// ## `flags`
    /// flags that define the behaviour of the subprocess
    ///
    /// # Returns
    ///
    /// A newly created [`Subprocess`][crate::Subprocess], or [`None`] on error (and `error`
    ///  will be set)
    #[doc(alias = "g_subprocess_newv")]
    pub fn newv(
        argv: &[&std::ffi::OsStr],
        flags: SubprocessFlags,
    ) -> Result<Subprocess, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_subprocess_newv(argv.to_glib_none().0, flags.into_glib(), &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Communicate with the subprocess until it terminates, and all input
    /// and output has been completed.
    ///
    /// If `stdin_buf` is given, the subprocess must have been created with
    /// [`SubprocessFlags::STDIN_PIPE`][crate::SubprocessFlags::STDIN_PIPE]. The given data is fed to the
    /// stdin of the subprocess and the pipe is closed (ie: EOF).
    ///
    /// At the same time (as not to cause blocking when dealing with large
    /// amounts of data), if [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE] or
    /// [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE] were used, reads from those
    /// streams. The data that was read is returned in `stdout` and/or
    /// the `stderr`.
    ///
    /// If the subprocess was created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
    /// `stdout_buf` will contain the data read from stdout. Otherwise, for
    /// subprocesses not created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
    /// `stdout_buf` will be set to [`None`]. Similar provisions apply to
    /// `stderr_buf` and [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE].
    ///
    /// As usual, any output variable may be given as [`None`] to ignore it.
    ///
    /// If you desire the stdout and stderr data to be interleaved, create
    /// the subprocess with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE] and
    /// [`SubprocessFlags::STDERR_MERGE`][crate::SubprocessFlags::STDERR_MERGE]. The merged result will be returned
    /// in `stdout_buf` and `stderr_buf` will be set to [`None`].
    ///
    /// In case of any error (including cancellation), [`false`] will be
    /// returned with `error` set. Some or all of the stdin data may have
    /// been written. Any stdout or stderr data that has been read will be
    /// discarded. None of the out variables (aside from `error`) will have
    /// been set to anything in particular and should not be inspected.
    ///
    /// In the case that [`true`] is returned, the subprocess has exited and the
    /// exit status inspection APIs (eg: [`has_exited()`][Self::has_exited()],
    /// [`exit_status()`][Self::exit_status()]) may be used.
    ///
    /// You should not attempt to use any of the subprocess pipes after
    /// starting this function, since they may be left in strange states,
    /// even if the operation was cancelled. You should especially not
    /// attempt to interact with the pipes while the operation is in progress
    /// (either from another thread or if using the asynchronous version).
    /// ## `stdin_buf`
    /// data to send to the stdin of the subprocess, or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable]
    ///
    /// # Returns
    ///
    /// [`true`] if successful
    ///
    /// ## `stdout_buf`
    /// data read from the subprocess stdout
    ///
    /// ## `stderr_buf`
    /// data read from the subprocess stderr
    #[doc(alias = "g_subprocess_communicate")]
    pub fn communicate(
        &self,
        stdin_buf: Option<&glib::Bytes>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error> {
        unsafe {
            let mut stdout_buf = ptr::null_mut();
            let mut stderr_buf = ptr::null_mut();
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_subprocess_communicate(
                self.to_glib_none().0,
                stdin_buf.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut stdout_buf,
                &mut stderr_buf,
                &mut error,
            );
            assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronous version of [`communicate()`][Self::communicate()]. Complete
    /// invocation with `g_subprocess_communicate_finish()`.
    /// ## `stdin_buf`
    /// Input data, or [`None`]
    /// ## `cancellable`
    /// Cancellable
    /// ## `callback`
    /// Callback
    #[doc(alias = "g_subprocess_communicate_async")]
    pub fn communicate_async<
        P: FnOnce(Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>) + 'static,
    >(
        &self,
        stdin_buf: Option<&glib::Bytes>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn communicate_async_trampoline<
            P: FnOnce(Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let mut stdout_buf = ptr::null_mut();
            let mut stderr_buf = ptr::null_mut();
            let _ = ffi::g_subprocess_communicate_finish(
                _source_object as *mut _,
                res,
                &mut stdout_buf,
                &mut stderr_buf,
                &mut error,
            );
            let result = if error.is_null() {
                Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = communicate_async_trampoline::<P>;
        unsafe {
            ffi::g_subprocess_communicate_async(
                self.to_glib_none().0,
                stdin_buf.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn communicate_future(
        &self,
        stdin_buf: Option<&glib::Bytes>,
    ) -> Pin<
        Box_<
            dyn std::future::Future<
                    Output = Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>,
                > + 'static,
        >,
    > {
        let stdin_buf = stdin_buf.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.communicate_async(
                    stdin_buf.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Like [`communicate()`][Self::communicate()], but validates the output of the
    /// process as UTF-8, and returns it as a regular NUL terminated string.
    ///
    /// On error, `stdout_buf` and `stderr_buf` will be set to undefined values and
    /// should not be used.
    /// ## `stdin_buf`
    /// data to send to the stdin of the subprocess, or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable]
    ///
    /// # Returns
    ///
    ///
    /// ## `stdout_buf`
    /// data read from the subprocess stdout
    ///
    /// ## `stderr_buf`
    /// data read from the subprocess stderr
    #[doc(alias = "g_subprocess_communicate_utf8")]
    pub fn communicate_utf8(
        &self,
        stdin_buf: Option<&str>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(Option<glib::GString>, Option<glib::GString>), glib::Error> {
        unsafe {
            let mut stdout_buf = ptr::null_mut();
            let mut stderr_buf = ptr::null_mut();
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_subprocess_communicate_utf8(
                self.to_glib_none().0,
                stdin_buf.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut stdout_buf,
                &mut stderr_buf,
                &mut error,
            );
            assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Use an operating-system specific method to attempt an immediate,
    /// forceful termination of the process. There is no mechanism to
    /// determine whether or not the request itself was successful;
    /// however, you can use [`wait()`][Self::wait()] to monitor the status of
    /// the process after calling this function.
    ///
    /// On Unix, this function sends `SIGKILL`.
    #[doc(alias = "g_subprocess_force_exit")]
    pub fn force_exit(&self) {
        unsafe {
            ffi::g_subprocess_force_exit(self.to_glib_none().0);
        }
    }

    /// Check the exit status of the subprocess, given that it exited
    /// normally. This is the value passed to the `exit()` system call or the
    /// return value from main.
    ///
    /// This is equivalent to the system WEXITSTATUS macro.
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] and
    /// unless [`has_exited()`][Self::has_exited()] returned [`true`].
    ///
    /// # Returns
    ///
    /// the exit status
    #[doc(alias = "g_subprocess_get_exit_status")]
    #[doc(alias = "get_exit_status")]
    pub fn exit_status(&self) -> i32 {
        unsafe { ffi::g_subprocess_get_exit_status(self.to_glib_none().0) }
    }

    /// On UNIX, returns the process ID as a decimal string.
    /// On Windows, returns the result of GetProcessId() also as a string.
    /// If the subprocess has terminated, this will return [`None`].
    ///
    /// # Returns
    ///
    /// the subprocess identifier, or [`None`] if the subprocess
    ///  has terminated
    #[doc(alias = "g_subprocess_get_identifier")]
    #[doc(alias = "get_identifier")]
    pub fn identifier(&self) -> Option<glib::GString> {
        unsafe { from_glib_none(ffi::g_subprocess_get_identifier(self.to_glib_none().0)) }
    }

    /// Check if the given subprocess exited normally (ie: by way of `exit()`
    /// or return from `main()`).
    ///
    /// This is equivalent to the system WIFEXITED macro.
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] has
    /// returned.
    ///
    /// # Returns
    ///
    /// [`true`] if the case of a normal exit
    #[doc(alias = "g_subprocess_get_if_exited")]
    #[doc(alias = "get_if_exited")]
    pub fn has_exited(&self) -> bool {
        unsafe { from_glib(ffi::g_subprocess_get_if_exited(self.to_glib_none().0)) }
    }

    /// Check if the given subprocess terminated in response to a signal.
    ///
    /// This is equivalent to the system WIFSIGNALED macro.
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] has
    /// returned.
    ///
    /// # Returns
    ///
    /// [`true`] if the case of termination due to a signal
    #[doc(alias = "g_subprocess_get_if_signaled")]
    #[doc(alias = "get_if_signaled")]
    pub fn has_signaled(&self) -> bool {
        unsafe { from_glib(ffi::g_subprocess_get_if_signaled(self.to_glib_none().0)) }
    }

    /// Gets the raw status code of the process, as from `waitpid()`.
    ///
    /// This value has no particular meaning, but it can be used with the
    /// macros defined by the system headers such as WIFEXITED. It can also
    /// be used with `g_spawn_check_wait_status()`.
    ///
    /// It is more likely that you want to use [`has_exited()`][Self::has_exited()]
    /// followed by [`exit_status()`][Self::exit_status()].
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] has
    /// returned.
    ///
    /// # Returns
    ///
    /// the (meaningless) `waitpid()` exit status from the kernel
    #[doc(alias = "g_subprocess_get_status")]
    #[doc(alias = "get_status")]
    pub fn status(&self) -> i32 {
        unsafe { ffi::g_subprocess_get_status(self.to_glib_none().0) }
    }

    /// Gets the [`InputStream`][crate::InputStream] from which to read the stderr output of
    /// `self`.
    ///
    /// The process must have been created with [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE],
    /// otherwise [`None`] will be returned.
    ///
    /// # Returns
    ///
    /// the stderr pipe
    #[doc(alias = "g_subprocess_get_stderr_pipe")]
    #[doc(alias = "get_stderr_pipe")]
    pub fn stderr_pipe(&self) -> Option<InputStream> {
        unsafe { from_glib_none(ffi::g_subprocess_get_stderr_pipe(self.to_glib_none().0)) }
    }

    /// Gets the [`OutputStream`][crate::OutputStream] that you can write to in order to give data
    /// to the stdin of `self`.
    ///
    /// The process must have been created with [`SubprocessFlags::STDIN_PIPE`][crate::SubprocessFlags::STDIN_PIPE] and
    /// not [`SubprocessFlags::STDIN_INHERIT`][crate::SubprocessFlags::STDIN_INHERIT], otherwise [`None`] will be returned.
    ///
    /// # Returns
    ///
    /// the stdout pipe
    #[doc(alias = "g_subprocess_get_stdin_pipe")]
    #[doc(alias = "get_stdin_pipe")]
    pub fn stdin_pipe(&self) -> Option<OutputStream> {
        unsafe { from_glib_none(ffi::g_subprocess_get_stdin_pipe(self.to_glib_none().0)) }
    }

    /// Gets the [`InputStream`][crate::InputStream] from which to read the stdout output of
    /// `self`.
    ///
    /// The process must have been created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
    /// otherwise [`None`] will be returned.
    ///
    /// # Returns
    ///
    /// the stdout pipe
    #[doc(alias = "g_subprocess_get_stdout_pipe")]
    #[doc(alias = "get_stdout_pipe")]
    pub fn stdout_pipe(&self) -> Option<InputStream> {
        unsafe { from_glib_none(ffi::g_subprocess_get_stdout_pipe(self.to_glib_none().0)) }
    }

    /// Checks if the process was "successful". A process is considered
    /// successful if it exited cleanly with an exit status of 0, either by
    /// way of the `exit()` system call or return from `main()`.
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] has
    /// returned.
    ///
    /// # Returns
    ///
    /// [`true`] if the process exited cleanly with a exit status of 0
    #[doc(alias = "g_subprocess_get_successful")]
    #[doc(alias = "get_successful")]
    pub fn is_successful(&self) -> bool {
        unsafe { from_glib(ffi::g_subprocess_get_successful(self.to_glib_none().0)) }
    }

    /// Get the signal number that caused the subprocess to terminate, given
    /// that it terminated due to a signal.
    ///
    /// This is equivalent to the system WTERMSIG macro.
    ///
    /// It is an error to call this function before [`wait()`][Self::wait()] and
    /// unless [`has_signaled()`][Self::has_signaled()] returned [`true`].
    ///
    /// # Returns
    ///
    /// the signal causing termination
    #[doc(alias = "g_subprocess_get_term_sig")]
    #[doc(alias = "get_term_sig")]
    pub fn term_sig(&self) -> i32 {
        unsafe { ffi::g_subprocess_get_term_sig(self.to_glib_none().0) }
    }

    /// Sends the UNIX signal `signal_num` to the subprocess, if it is still
    /// running.
    ///
    /// This API is race-free. If the subprocess has terminated, it will not
    /// be signalled.
    ///
    /// This API is not available on Windows.
    /// ## `signal_num`
    /// the signal number to send
    #[cfg(any(not(windows), feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(not(windows))))]
    #[doc(alias = "g_subprocess_send_signal")]
    pub fn send_signal(&self, signal_num: i32) {
        unsafe {
            ffi::g_subprocess_send_signal(self.to_glib_none().0, signal_num);
        }
    }

    /// Synchronously wait for the subprocess to terminate.
    ///
    /// After the process terminates you can query its exit status with
    /// functions such as [`has_exited()`][Self::has_exited()] and
    /// [`exit_status()`][Self::exit_status()].
    ///
    /// This function does not fail in the case of the subprocess having
    /// abnormal termination. See [`wait_check()`][Self::wait_check()] for that.
    ///
    /// Cancelling `cancellable` doesn't kill the subprocess. Call
    /// [`force_exit()`][Self::force_exit()] if it is desirable.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if `cancellable` was cancelled
    #[doc(alias = "g_subprocess_wait")]
    pub fn wait(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_subprocess_wait(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Wait for the subprocess to terminate.
    ///
    /// This is the asynchronous version of [`wait()`][Self::wait()].
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable], or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the operation is complete
    #[doc(alias = "g_subprocess_wait_async")]
    pub fn wait_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn wait_async_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let _ = ffi::g_subprocess_wait_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = wait_async_trampoline::<P>;
        unsafe {
            ffi::g_subprocess_wait_async(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn wait_future(
        &self,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.wait_async(Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    /// Combines [`wait()`][Self::wait()] with `g_spawn_check_wait_status()`.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if process exited abnormally, or
    /// `cancellable` was cancelled
    #[doc(alias = "g_subprocess_wait_check")]
    pub fn wait_check(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_subprocess_wait_check(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Combines [`wait_async()`][Self::wait_async()] with `g_spawn_check_wait_status()`.
    ///
    /// This is the asynchronous version of [`wait_check()`][Self::wait_check()].
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable], or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the operation is complete
    #[doc(alias = "g_subprocess_wait_check_async")]
    pub fn wait_check_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn wait_check_async_trampoline<
            P: FnOnce(Result<(), glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let _ = ffi::g_subprocess_wait_check_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = wait_check_async_trampoline::<P>;
        unsafe {
            ffi::g_subprocess_wait_check_async(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn wait_check_future(
        &self,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.wait_check_async(Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }
}

impl fmt::Display for Subprocess {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Subprocess")
    }
}