1//! Unix-specific extensions to primitives in the [`std::process`] module.
2//!
3//! [`std::process`]: crate::process
4
5#![stable(feature = "rust1", since = "1.0.0")]
6
7use crate::ffi::OsStr;
8use crate::io;
9use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
10use crate::process;
11use crate::sealed::Sealed;
12use crate::sys;
13use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
14
15use cfg_if::cfg_if;
16
17cfg_if! {
18 if #[cfg(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon", target_os = "vita"))] {
19 type UserId = u16;
20 type GroupId = u16;
21 } else if #[cfg(target_os = "nto")] {
22 // Both IDs are signed, see `sys/target_nto.h` of the QNX Neutrino SDP.
23 // Only positive values should be used, see e.g.
24 // https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.neutrino.lib_ref/topic/s/setuid.html
25 type UserId = i32;
26 type GroupId = i32;
27 } else {
28 type UserId = u32;
29 type GroupId = u32;
30 }
31}
32
33/// Unix-specific extensions to the [`process::Command`] builder.
34///
35/// This trait is sealed: it cannot be implemented outside the standard library.
36/// This is so that future additional methods are not breaking changes.
37#[stable(feature = "rust1", since = "1.0.0")]
38pub trait CommandExt: Sealed {
39 /// Sets the child process's user ID. This translates to a
40 /// `setuid` call in the child process. Failure in the `setuid`
41 /// call will cause the spawn to fail.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 fn uid(&mut self, id: UserId) -> &mut process::Command;
44
45 /// Similar to `uid`, but sets the group ID of the child process. This has
46 /// the same semantics as the `uid` field.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 fn gid(&mut self, id: GroupId) -> &mut process::Command;
49
50 /// Sets the supplementary group IDs for the calling process. Translates to
51 /// a `setgroups` call in the child process.
52 #[unstable(feature = "setgroups", issue = "90747")]
53 fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command;
54
55 /// Schedules a closure to be run just before the `exec` function is
56 /// invoked.
57 ///
58 /// The closure is allowed to return an I/O error whose OS error code will
59 /// be communicated back to the parent and returned as an error from when
60 /// the spawn was requested.
61 ///
62 /// Multiple closures can be registered and they will be called in order of
63 /// their registration. If a closure returns `Err` then no further closures
64 /// will be called and the spawn operation will immediately return with a
65 /// failure.
66 ///
67 /// # Notes and Safety
68 ///
69 /// This closure will be run in the context of the child process after a
70 /// `fork`. This primarily means that any modifications made to memory on
71 /// behalf of this closure will **not** be visible to the parent process.
72 /// This is often a very constrained environment where normal operations
73 /// like `malloc`, accessing environment variables through [`std::env`]
74 /// or acquiring a mutex are not guaranteed to work (due to
75 /// other threads perhaps still running when the `fork` was run).
76 ///
77 /// For further details refer to the [POSIX fork() specification]
78 /// and the equivalent documentation for any targeted
79 /// platform, especially the requirements around *async-signal-safety*.
80 ///
81 /// This also means that all resources such as file descriptors and
82 /// memory-mapped regions got duplicated. It is your responsibility to make
83 /// sure that the closure does not violate library invariants by making
84 /// invalid use of these duplicates.
85 ///
86 /// Panicking in the closure is safe only if all the format arguments for the
87 /// panic message can be safely formatted; this is because although
88 /// `Command` calls [`std::panic::always_abort`](crate::panic::always_abort)
89 /// before calling the pre_exec hook, panic will still try to format the
90 /// panic message.
91 ///
92 /// When this closure is run, aspects such as the stdio file descriptors and
93 /// working directory have successfully been changed, so output to these
94 /// locations might not appear where intended.
95 ///
96 /// [POSIX fork() specification]:
97 /// https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html
98 /// [`std::env`]: mod@crate::env
99 #[stable(feature = "process_pre_exec", since = "1.34.0")]
100 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
101 where
102 F: FnMut() -> io::Result<()> + Send + Sync + 'static;
103
104 /// Schedules a closure to be run just before the `exec` function is
105 /// invoked.
106 ///
107 /// This method is stable and usable, but it should be unsafe. To fix
108 /// that, it got deprecated in favor of the unsafe [`pre_exec`].
109 ///
110 /// [`pre_exec`]: CommandExt::pre_exec
111 #[stable(feature = "process_exec", since = "1.15.0")]
112 #[deprecated(since = "1.37.0", note = "should be unsafe, use `pre_exec` instead")]
113 fn before_exec<F>(&mut self, f: F) -> &mut process::Command
114 where
115 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
116 {
117 unsafe { self.pre_exec(f) }
118 }
119
120 /// Performs all the required setup by this `Command`, followed by calling
121 /// the `execvp` syscall.
122 ///
123 /// On success this function will not return, and otherwise it will return
124 /// an error indicating why the exec (or another part of the setup of the
125 /// `Command`) failed.
126 ///
127 /// `exec` not returning has the same implications as calling
128 /// [`process::exit`] – no destructors on the current stack or any other
129 /// thread’s stack will be run. Therefore, it is recommended to only call
130 /// `exec` at a point where it is fine to not run any destructors. Note,
131 /// that the `execvp` syscall independently guarantees that all memory is
132 /// freed and all file descriptors with the `CLOEXEC` option (set by default
133 /// on all file descriptors opened by the standard library) are closed.
134 ///
135 /// This function, unlike `spawn`, will **not** `fork` the process to create
136 /// a new child. Like spawn, however, the default behavior for the stdio
137 /// descriptors will be to inherited from the current process.
138 ///
139 /// # Notes
140 ///
141 /// The process may be in a "broken state" if this function returns in
142 /// error. For example the working directory, environment variables, signal
143 /// handling settings, various user/group information, or aspects of stdio
144 /// file descriptors may have changed. If a "transactional spawn" is
145 /// required to gracefully handle errors it is recommended to use the
146 /// cross-platform `spawn` instead.
147 #[stable(feature = "process_exec2", since = "1.9.0")]
148 fn exec(&mut self) -> io::Error;
149
150 /// Set executable argument
151 ///
152 /// Set the first process argument, `argv[0]`, to something other than the
153 /// default executable path.
154 #[stable(feature = "process_set_argv0", since = "1.45.0")]
155 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
156 where
157 S: AsRef<OsStr>;
158
159 /// Sets the process group ID (PGID) of the child process. Equivalent to a
160 /// `setpgid` call in the child process, but may be more efficient.
161 ///
162 /// Process groups determine which processes receive signals.
163 ///
164 /// # Examples
165 ///
166 /// Pressing Ctrl-C in a terminal will send SIGINT to all processes in
167 /// the current foreground process group. By spawning the `sleep`
168 /// subprocess in a new process group, it will not receive SIGINT from the
169 /// terminal.
170 ///
171 /// The parent process could install a signal handler and manage the
172 /// subprocess on its own terms.
173 ///
174 /// A process group ID of 0 will use the process ID as the PGID.
175 ///
176 /// ```no_run
177 /// use std::process::Command;
178 /// use std::os::unix::process::CommandExt;
179 ///
180 /// Command::new("sleep")
181 /// .arg("10")
182 /// .process_group(0)
183 /// .spawn()?
184 /// .wait()?;
185 /// #
186 /// # Ok::<_, Box<dyn std::error::Error>>(())
187 /// ```
188 #[stable(feature = "process_set_process_group", since = "1.64.0")]
189 fn process_group(&mut self, pgroup: i32) -> &mut process::Command;
190}
191
192#[stable(feature = "rust1", since = "1.0.0")]
193impl CommandExt for process::Command {
194 fn uid(&mut self, id: UserId) -> &mut process::Command {
195 self.as_inner_mut().uid(id);
196 self
197 }
198
199 fn gid(&mut self, id: GroupId) -> &mut process::Command {
200 self.as_inner_mut().gid(id);
201 self
202 }
203
204 fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command {
205 self.as_inner_mut().groups(groups);
206 self
207 }
208
209 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
210 where
211 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
212 {
213 self.as_inner_mut().pre_exec(Box::new(f));
214 self
215 }
216
217 fn exec(&mut self) -> io::Error {
218 // NOTE: This may *not* be safe to call after `libc::fork`, because it
219 // may allocate. That may be worth fixing at some point in the future.
220 self.as_inner_mut().exec(sys::process::Stdio::Inherit)
221 }
222
223 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
224 where
225 S: AsRef<OsStr>,
226 {
227 self.as_inner_mut().set_arg_0(arg.as_ref());
228 self
229 }
230
231 fn process_group(&mut self, pgroup: i32) -> &mut process::Command {
232 self.as_inner_mut().pgroup(pgroup);
233 self
234 }
235}
236
237/// Unix-specific extensions to [`process::ExitStatus`] and
238/// [`ExitStatusError`](process::ExitStatusError).
239///
240/// On Unix, `ExitStatus` **does not necessarily represent an exit status**, as
241/// passed to the `_exit` system call or returned by
242/// [`ExitStatus::code()`](crate::process::ExitStatus::code). It represents **any wait status**
243/// as returned by one of the `wait` family of system
244/// calls.
245///
246/// A Unix wait status (a Rust `ExitStatus`) can represent a Unix exit status, but can also
247/// represent other kinds of process event.
248///
249/// This trait is sealed: it cannot be implemented outside the standard library.
250/// This is so that future additional methods are not breaking changes.
251#[stable(feature = "rust1", since = "1.0.0")]
252pub trait ExitStatusExt: Sealed {
253 /// Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status
254 /// value from `wait`
255 ///
256 /// The value should be a **wait status, not an exit status**.
257 ///
258 /// # Panics
259 ///
260 /// Panics on an attempt to make an `ExitStatusError` from a wait status of `0`.
261 ///
262 /// Making an `ExitStatus` always succeeds and never panics.
263 #[stable(feature = "exit_status_from", since = "1.12.0")]
264 fn from_raw(raw: i32) -> Self;
265
266 /// If the process was terminated by a signal, returns that signal.
267 ///
268 /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`.
269 #[stable(feature = "rust1", since = "1.0.0")]
270 fn signal(&self) -> Option<i32>;
271
272 /// If the process was terminated by a signal, says whether it dumped core.
273 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
274 fn core_dumped(&self) -> bool;
275
276 /// If the process was stopped by a signal, returns that signal.
277 ///
278 /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from
279 /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`.
280 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
281 fn stopped_signal(&self) -> Option<i32>;
282
283 /// Whether the process was continued from a stopped status.
284 ///
285 /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call
286 /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`.
287 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
288 fn continued(&self) -> bool;
289
290 /// Returns the underlying raw `wait` status.
291 ///
292 /// The returned integer is a **wait status, not an exit status**.
293 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
294 fn into_raw(self) -> i32;
295}
296
297#[stable(feature = "rust1", since = "1.0.0")]
298impl ExitStatusExt for process::ExitStatus {
299 fn from_raw(raw: i32) -> Self {
300 process::ExitStatus::from_inner(From::from(raw))
301 }
302
303 fn signal(&self) -> Option<i32> {
304 self.as_inner().signal()
305 }
306
307 fn core_dumped(&self) -> bool {
308 self.as_inner().core_dumped()
309 }
310
311 fn stopped_signal(&self) -> Option<i32> {
312 self.as_inner().stopped_signal()
313 }
314
315 fn continued(&self) -> bool {
316 self.as_inner().continued()
317 }
318
319 fn into_raw(self) -> i32 {
320 self.as_inner().into_raw().into()
321 }
322}
323
324#[unstable(feature = "exit_status_error", issue = "84908")]
325impl ExitStatusExt for process::ExitStatusError {
326 fn from_raw(raw: i32) -> Self {
327 process::ExitStatus::from_raw(raw)
328 .exit_ok()
329 .expect_err("<ExitStatusError as ExitStatusExt>::from_raw(0) but zero is not an error")
330 }
331
332 fn signal(&self) -> Option<i32> {
333 self.into_status().signal()
334 }
335
336 fn core_dumped(&self) -> bool {
337 self.into_status().core_dumped()
338 }
339
340 fn stopped_signal(&self) -> Option<i32> {
341 self.into_status().stopped_signal()
342 }
343
344 fn continued(&self) -> bool {
345 self.into_status().continued()
346 }
347
348 fn into_raw(self) -> i32 {
349 self.into_status().into_raw()
350 }
351}
352
353#[stable(feature = "process_extensions", since = "1.2.0")]
354impl FromRawFd for process::Stdio {
355 #[inline]
356 unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio {
357 let fd: FileDesc = sys::fd::FileDesc::from_raw_fd(fd);
358 let io: Stdio = sys::process::Stdio::Fd(fd);
359 process::Stdio::from_inner(io)
360 }
361}
362
363#[stable(feature = "io_safety", since = "1.63.0")]
364impl From<OwnedFd> for process::Stdio {
365 #[inline]
366 fn from(fd: OwnedFd) -> process::Stdio {
367 let fd: FileDesc = sys::fd::FileDesc::from_inner(fd);
368 let io: Stdio = sys::process::Stdio::Fd(fd);
369 process::Stdio::from_inner(io)
370 }
371}
372
373#[stable(feature = "process_extensions", since = "1.2.0")]
374impl AsRawFd for process::ChildStdin {
375 #[inline]
376 fn as_raw_fd(&self) -> RawFd {
377 self.as_inner().as_raw_fd()
378 }
379}
380
381#[stable(feature = "process_extensions", since = "1.2.0")]
382impl AsRawFd for process::ChildStdout {
383 #[inline]
384 fn as_raw_fd(&self) -> RawFd {
385 self.as_inner().as_raw_fd()
386 }
387}
388
389#[stable(feature = "process_extensions", since = "1.2.0")]
390impl AsRawFd for process::ChildStderr {
391 #[inline]
392 fn as_raw_fd(&self) -> RawFd {
393 self.as_inner().as_raw_fd()
394 }
395}
396
397#[stable(feature = "into_raw_os", since = "1.4.0")]
398impl IntoRawFd for process::ChildStdin {
399 #[inline]
400 fn into_raw_fd(self) -> RawFd {
401 self.into_inner().into_inner().into_raw_fd()
402 }
403}
404
405#[stable(feature = "into_raw_os", since = "1.4.0")]
406impl IntoRawFd for process::ChildStdout {
407 #[inline]
408 fn into_raw_fd(self) -> RawFd {
409 self.into_inner().into_inner().into_raw_fd()
410 }
411}
412
413#[stable(feature = "into_raw_os", since = "1.4.0")]
414impl IntoRawFd for process::ChildStderr {
415 #[inline]
416 fn into_raw_fd(self) -> RawFd {
417 self.into_inner().into_inner().into_raw_fd()
418 }
419}
420
421#[stable(feature = "io_safety", since = "1.63.0")]
422impl AsFd for crate::process::ChildStdin {
423 #[inline]
424 fn as_fd(&self) -> BorrowedFd<'_> {
425 self.as_inner().as_fd()
426 }
427}
428
429#[stable(feature = "io_safety", since = "1.63.0")]
430impl From<crate::process::ChildStdin> for OwnedFd {
431 #[inline]
432 fn from(child_stdin: crate::process::ChildStdin) -> OwnedFd {
433 child_stdin.into_inner().into_inner().into_inner()
434 }
435}
436
437/// Create a `ChildStdin` from the provided `OwnedFd`.
438///
439/// The provided file descriptor must point to a pipe
440/// with the `CLOEXEC` flag set.
441#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
442impl From<OwnedFd> for process::ChildStdin {
443 #[inline]
444 fn from(fd: OwnedFd) -> process::ChildStdin {
445 let fd: FileDesc = sys::fd::FileDesc::from_inner(fd);
446 let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd);
447 process::ChildStdin::from_inner(pipe)
448 }
449}
450
451#[stable(feature = "io_safety", since = "1.63.0")]
452impl AsFd for crate::process::ChildStdout {
453 #[inline]
454 fn as_fd(&self) -> BorrowedFd<'_> {
455 self.as_inner().as_fd()
456 }
457}
458
459#[stable(feature = "io_safety", since = "1.63.0")]
460impl From<crate::process::ChildStdout> for OwnedFd {
461 #[inline]
462 fn from(child_stdout: crate::process::ChildStdout) -> OwnedFd {
463 child_stdout.into_inner().into_inner().into_inner()
464 }
465}
466
467/// Create a `ChildStdout` from the provided `OwnedFd`.
468///
469/// The provided file descriptor must point to a pipe
470/// with the `CLOEXEC` flag set.
471#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
472impl From<OwnedFd> for process::ChildStdout {
473 #[inline]
474 fn from(fd: OwnedFd) -> process::ChildStdout {
475 let fd: FileDesc = sys::fd::FileDesc::from_inner(fd);
476 let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd);
477 process::ChildStdout::from_inner(pipe)
478 }
479}
480
481#[stable(feature = "io_safety", since = "1.63.0")]
482impl AsFd for crate::process::ChildStderr {
483 #[inline]
484 fn as_fd(&self) -> BorrowedFd<'_> {
485 self.as_inner().as_fd()
486 }
487}
488
489#[stable(feature = "io_safety", since = "1.63.0")]
490impl From<crate::process::ChildStderr> for OwnedFd {
491 #[inline]
492 fn from(child_stderr: crate::process::ChildStderr) -> OwnedFd {
493 child_stderr.into_inner().into_inner().into_inner()
494 }
495}
496
497/// Create a `ChildStderr` from the provided `OwnedFd`.
498///
499/// The provided file descriptor must point to a pipe
500/// with the `CLOEXEC` flag set.
501#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
502impl From<OwnedFd> for process::ChildStderr {
503 #[inline]
504 fn from(fd: OwnedFd) -> process::ChildStderr {
505 let fd: FileDesc = sys::fd::FileDesc::from_inner(fd);
506 let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd);
507 process::ChildStderr::from_inner(pipe)
508 }
509}
510
511/// Returns the OS-assigned process identifier associated with this process's parent.
512#[must_use]
513#[stable(feature = "unix_ppid", since = "1.27.0")]
514pub fn parent_id() -> u32 {
515 crate::sys::os::getppid()
516}
517