Skip to main content

gio/
subprocess_launcher.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3#[cfg(any(unix, all(docsrs, unix)))]
4use std::os::unix::io::{AsFd, AsRawFd, IntoRawFd, OwnedFd};
5
6use glib::translate::*;
7
8use crate::ffi;
9use crate::{IOErrorEnum, Subprocess, SubprocessLauncher};
10
11#[cfg(all(docsrs, not(unix)))]
12pub trait IntoRawFd: Sized {
13    fn into_raw_fd(self) -> i32 {
14        0
15    }
16}
17
18impl SubprocessLauncher {
19    /// Creates a #GSubprocess given a provided varargs list of arguments.
20    /// ## `error`
21    /// Error
22    /// ## `argv0`
23    /// Command line arguments
24    ///
25    /// # Returns
26    ///
27    /// A new #GSubprocess, or [`None`] on error (and @error will be set)
28    #[doc(alias = "g_subprocess_launcher_spawnv")]
29    #[doc(alias = "spawnv")]
30    pub fn spawn(&self, argv: &[&std::ffi::OsStr]) -> Result<Subprocess, glib::Error> {
31        if argv.is_empty() || argv[0].is_empty() {
32            return Err(glib::Error::new(
33                IOErrorEnum::InvalidArgument,
34                "argv must contain at least one non-empty element",
35            ));
36        }
37
38        unsafe {
39            let mut error = std::ptr::null_mut();
40            let ret = ffi::g_subprocess_launcher_spawnv(
41                self.to_glib_none().0,
42                argv.to_glib_none().0,
43                &mut error,
44            );
45            if !error.is_null() {
46                Err(from_glib_full(error))
47            } else if ret.is_null() {
48                Err(glib::Error::new(
49                    IOErrorEnum::InvalidArgument,
50                    "g_subprocess_launcher_spawnv() returned NULL without setting an error",
51                ))
52            } else {
53                Ok(from_glib_full(ret))
54            }
55        }
56    }
57
58    /// Replace the entire environment of processes launched from this
59    /// launcher with the given 'environ' variable.
60    ///
61    /// Typically you will build this variable by using g_listenv() to copy
62    /// the process 'environ' and using the functions g_environ_setenv(),
63    /// g_environ_unsetenv(), etc.
64    ///
65    /// As an alternative, you can use g_subprocess_launcher_setenv(),
66    /// g_subprocess_launcher_unsetenv(), etc.
67    ///
68    /// Pass an empty array to set an empty environment. Pass [`None`] to inherit the
69    /// parent process’ environment. As of GLib 2.54, the parent process’ environment
70    /// will be copied when g_subprocess_launcher_set_environ() is called.
71    /// Previously, it was copied when the subprocess was executed. This means the
72    /// copied environment may now be modified (using g_subprocess_launcher_setenv(),
73    /// etc.) before launching the subprocess.
74    ///
75    /// On UNIX, all strings in this array can be arbitrary byte strings.
76    /// On Windows, they should be in UTF-8.
77    /// ## `env`
78    ///
79    ///     the replacement environment
80    #[doc(alias = "g_subprocess_launcher_set_environ")]
81    pub fn set_environ(&self, env: &[std::ffi::OsString]) {
82        unsafe {
83            ffi::g_subprocess_launcher_set_environ(self.to_glib_none().0, env.to_glib_none().0);
84        }
85    }
86
87    /// Transfer an arbitrary file descriptor from parent process to the
88    /// child.  This function takes ownership of the @source_fd; it will be closed
89    /// in the parent when @self is freed.
90    ///
91    /// By default, all file descriptors from the parent will be closed.
92    /// This function allows you to create (for example) a custom `pipe()` or
93    /// `socketpair()` before launching the process, and choose the target
94    /// descriptor in the child.
95    ///
96    /// An example use case is GNUPG, which has a command line argument
97    /// `--passphrase-fd` providing a file descriptor number where it expects
98    /// the passphrase to be written.
99    /// ## `source_fd`
100    /// File descriptor in parent process
101    /// ## `target_fd`
102    /// Target descriptor for child process
103    #[cfg(unix)]
104    #[cfg_attr(docsrs, doc(cfg(unix)))]
105    #[doc(alias = "g_subprocess_launcher_take_fd")]
106    pub fn take_fd(&self, source_fd: OwnedFd, target_fd: impl AsFd) {
107        let source_raw_fd = source_fd.into_raw_fd();
108        let target_raw_fd = target_fd.as_fd().as_raw_fd();
109        unsafe {
110            ffi::g_subprocess_launcher_take_fd(self.to_glib_none().0, source_raw_fd, target_raw_fd);
111        }
112    }
113
114    /// Sets the file descriptor to use as the stderr for spawned processes.
115    ///
116    /// If @fd is -1 then any previously given fd is unset.
117    ///
118    /// Note that the default behaviour is to pass stderr through to the
119    /// stderr of the parent process.
120    ///
121    /// The passed @fd belongs to the #GSubprocessLauncher.  It will be
122    /// automatically closed when the launcher is finalized.  The file
123    /// descriptor will also be closed on the child side when executing the
124    /// spawned process.
125    ///
126    /// You may not set a stderr fd if a stderr file path is already set or
127    /// if the launcher flags contain any flags directing stderr elsewhere.
128    ///
129    /// This feature is only available on UNIX.
130    /// ## `fd`
131    /// a file descriptor, or -1
132    #[cfg(unix)]
133    #[cfg_attr(docsrs, doc(cfg(unix)))]
134    #[doc(alias = "g_subprocess_launcher_take_stderr_fd")]
135    pub fn take_stderr_fd(&self, fd: Option<OwnedFd>) {
136        unsafe {
137            let raw_fd = fd.map_or(-1, |fd| fd.into_raw_fd());
138            ffi::g_subprocess_launcher_take_stderr_fd(self.to_glib_none().0, raw_fd);
139        }
140    }
141
142    /// Sets the file descriptor to use as the stdin for spawned processes.
143    ///
144    /// If @fd is -1 then any previously given fd is unset.
145    ///
146    /// Note that if your intention is to have the stdin of the calling
147    /// process inherited by the child then [`SubprocessFlags::STDIN_INHERIT`][crate::SubprocessFlags::STDIN_INHERIT]
148    /// is a better way to go about doing that.
149    ///
150    /// The passed @fd is noted but will not be touched in the current
151    /// process.  It is therefore necessary that it be kept open by the
152    /// caller until the subprocess is spawned.  The file descriptor will
153    /// also not be explicitly closed on the child side, so it must be marked
154    /// O_CLOEXEC if that's what you want.
155    ///
156    /// You may not set a stdin fd if a stdin file path is already set or if
157    /// the launcher flags contain any flags directing stdin elsewhere.
158    ///
159    /// This feature is only available on UNIX.
160    /// ## `fd`
161    /// a file descriptor, or -1
162    #[cfg(unix)]
163    #[cfg_attr(docsrs, doc(cfg(unix)))]
164    #[doc(alias = "g_subprocess_launcher_take_stdin_fd")]
165    pub fn take_stdin_fd(&self, fd: Option<OwnedFd>) {
166        let raw_fd = fd.map_or(-1, |fd| fd.into_raw_fd());
167        unsafe {
168            ffi::g_subprocess_launcher_take_stdin_fd(self.to_glib_none().0, raw_fd);
169        }
170    }
171
172    /// Sets the file descriptor to use as the stdout for spawned processes.
173    ///
174    /// If @fd is -1 then any previously given fd is unset.
175    ///
176    /// Note that the default behaviour is to pass stdout through to the
177    /// stdout of the parent process.
178    ///
179    /// The passed @fd is noted but will not be touched in the current
180    /// process.  It is therefore necessary that it be kept open by the
181    /// caller until the subprocess is spawned.  The file descriptor will
182    /// also not be explicitly closed on the child side, so it must be marked
183    /// O_CLOEXEC if that's what you want.
184    ///
185    /// You may not set a stdout fd if a stdout file path is already set or
186    /// if the launcher flags contain any flags directing stdout elsewhere.
187    ///
188    /// This feature is only available on UNIX.
189    /// ## `fd`
190    /// a file descriptor, or -1
191    #[cfg(unix)]
192    #[cfg_attr(docsrs, doc(cfg(unix)))]
193    #[doc(alias = "g_subprocess_launcher_take_stdout_fd")]
194    pub fn take_stdout_fd(&self, fd: Option<OwnedFd>) {
195        let raw_fd = fd.map_or(-1, |fd| fd.into_raw_fd());
196        unsafe {
197            ffi::g_subprocess_launcher_take_stdout_fd(self.to_glib_none().0, raw_fd);
198        }
199    }
200}