std/os/unix/
process.rs

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