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