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