std/os/linux/
process.rs

1//! Linux-specific extensions to primitives in the [`std::process`] module.
2//!
3//! [`std::process`]: crate::process
4
5#![unstable(feature = "linux_pidfd", issue = "82971")]
6
7use crate::io::Result;
8use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
9use crate::process::{self, ExitStatus};
10use crate::sealed::Sealed;
11use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner};
12#[cfg(not(doc))]
13use crate::sys::{fd::FileDesc, linux::pidfd::PidFd as InnerPidFd};
14
15#[cfg(doc)]
16struct InnerPidFd;
17
18/// This type represents a file descriptor that refers to a process.
19///
20/// A `PidFd` can be obtained by setting the corresponding option on [`Command`]
21/// with [`create_pidfd`]. Subsequently, the created pidfd can be retrieved
22/// from the [`Child`] by calling [`pidfd`] or [`into_pidfd`].
23///
24/// Example:
25/// ```no_run
26/// #![feature(linux_pidfd)]
27/// use std::os::linux::process::{CommandExt, ChildExt};
28/// use std::process::Command;
29///
30/// let mut child = Command::new("echo")
31///     .create_pidfd(true)
32///     .spawn()
33///     .expect("Failed to spawn child");
34///
35/// let pidfd = child
36///     .into_pidfd()
37///     .expect("Failed to retrieve pidfd");
38///
39/// // The file descriptor will be closed when `pidfd` is dropped.
40/// ```
41/// Refer to the man page of [`pidfd_open(2)`] for further details.
42///
43/// [`Command`]: process::Command
44/// [`create_pidfd`]: CommandExt::create_pidfd
45/// [`Child`]: process::Child
46/// [`pidfd`]: fn@ChildExt::pidfd
47/// [`into_pidfd`]: ChildExt::into_pidfd
48/// [`pidfd_open(2)`]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
49#[derive(Debug)]
50#[repr(transparent)]
51pub struct PidFd {
52    inner: InnerPidFd,
53}
54
55impl PidFd {
56    /// Forces the child process to exit.
57    ///
58    /// Unlike [`Child::kill`] it is possible to attempt to kill
59    /// reaped children since PidFd does not suffer from pid recycling
60    /// races. But doing so will return an Error.
61    ///
62    /// [`Child::kill`]: process::Child::kill
63    pub fn kill(&self) -> Result<()> {
64        self.inner.kill()
65    }
66
67    /// Waits for the child to exit completely, returning the status that it exited with.
68    ///
69    /// Unlike [`Child::wait`] it does not ensure that the stdin handle is closed.
70    ///
71    /// Additionally on kernels prior to 6.15 only the first attempt to
72    /// reap a child will return an ExitStatus, further attempts
73    /// will return an Error.
74    ///
75    /// [`Child::wait`]: process::Child::wait
76    pub fn wait(&self) -> Result<ExitStatus> {
77        self.inner.wait().map(FromInner::from_inner)
78    }
79
80    /// Attempts to collect the exit status of the child if it has already exited.
81    ///
82    /// On kernels prior to 6.15, and unlike [`Child::try_wait`], only the first attempt
83    /// to reap a child will return an ExitStatus, further attempts will return an Error.
84    ///
85    /// [`Child::try_wait`]: process::Child::try_wait
86    pub fn try_wait(&self) -> Result<Option<ExitStatus>> {
87        Ok(self.inner.try_wait()?.map(FromInner::from_inner))
88    }
89}
90
91impl AsInner<InnerPidFd> for PidFd {
92    #[inline]
93    fn as_inner(&self) -> &InnerPidFd {
94        &self.inner
95    }
96}
97
98impl FromInner<InnerPidFd> for PidFd {
99    fn from_inner(inner: InnerPidFd) -> PidFd {
100        PidFd { inner }
101    }
102}
103
104impl IntoInner<InnerPidFd> for PidFd {
105    fn into_inner(self) -> InnerPidFd {
106        self.inner
107    }
108}
109
110impl AsRawFd for PidFd {
111    #[inline]
112    fn as_raw_fd(&self) -> RawFd {
113        self.as_inner().as_inner().as_raw_fd()
114    }
115}
116
117impl FromRawFd for PidFd {
118    unsafe fn from_raw_fd(fd: RawFd) -> Self {
119        Self::from_inner(InnerPidFd::from_raw_fd(fd))
120    }
121}
122
123impl IntoRawFd for PidFd {
124    fn into_raw_fd(self) -> RawFd {
125        self.into_inner().into_inner().into_raw_fd()
126    }
127}
128
129impl AsFd for PidFd {
130    fn as_fd(&self) -> BorrowedFd<'_> {
131        self.as_inner().as_inner().as_fd()
132    }
133}
134
135impl From<OwnedFd> for PidFd {
136    fn from(fd: OwnedFd) -> Self {
137        Self::from_inner(InnerPidFd::from_inner(FileDesc::from_inner(fd)))
138    }
139}
140
141impl From<PidFd> for OwnedFd {
142    fn from(pid_fd: PidFd) -> Self {
143        pid_fd.into_inner().into_inner().into_inner()
144    }
145}
146
147/// Os-specific extensions for [`Child`]
148///
149/// [`Child`]: process::Child
150pub trait ChildExt: Sealed {
151    /// Obtains a reference to the [`PidFd`] created for this [`Child`], if available.
152    ///
153    /// A pidfd will only be available if its creation was requested with
154    /// [`create_pidfd`] when the corresponding [`Command`] was created.
155    ///
156    /// Even if requested, a pidfd may not be available due to an older
157    /// version of Linux being in use, or if some other error occurred.
158    ///
159    /// [`Command`]: process::Command
160    /// [`create_pidfd`]: CommandExt::create_pidfd
161    /// [`Child`]: process::Child
162    fn pidfd(&self) -> Result<&PidFd>;
163
164    /// Returns the [`PidFd`] created for this [`Child`], if available.
165    /// Otherwise self is returned.
166    ///
167    /// A pidfd will only be available if its creation was requested with
168    /// [`create_pidfd`] when the corresponding [`Command`] was created.
169    ///
170    /// Taking ownership of the PidFd consumes the Child to avoid pid reuse
171    /// races. Use [`pidfd`] and [`BorrowedFd::try_clone_to_owned`] if
172    /// you don't want to disassemble the Child yet.
173    ///
174    /// Even if requested, a pidfd may not be available due to an older
175    /// version of Linux being in use, or if some other error occurred.
176    ///
177    /// [`Command`]: process::Command
178    /// [`create_pidfd`]: CommandExt::create_pidfd
179    /// [`pidfd`]: ChildExt::pidfd
180    /// [`Child`]: process::Child
181    fn into_pidfd(self) -> crate::result::Result<PidFd, Self>
182    where
183        Self: Sized;
184}
185
186/// Os-specific extensions for [`Command`]
187///
188/// [`Command`]: process::Command
189pub trait CommandExt: Sealed {
190    /// Sets whether a [`PidFd`](struct@PidFd) should be created for the [`Child`]
191    /// spawned by this [`Command`].
192    /// By default, no pidfd will be created.
193    ///
194    /// The pidfd can be retrieved from the child with [`pidfd`] or [`into_pidfd`].
195    ///
196    /// A pidfd will only be created if it is possible to do so
197    /// in a guaranteed race-free manner. Otherwise, [`pidfd`] will return an error.
198    ///
199    /// If a pidfd has been successfully created and not been taken from the `Child`
200    /// then calls to `kill()`, `wait()` and `try_wait()` will use the pidfd
201    /// instead of the pid. This can prevent pid recycling races, e.g.
202    /// those  caused by rogue libraries in the same process prematurely reaping
203    /// zombie children via `waitpid(-1, ...)` calls.
204    ///
205    /// [`Command`]: process::Command
206    /// [`Child`]: process::Child
207    /// [`pidfd`]: fn@ChildExt::pidfd
208    /// [`into_pidfd`]: ChildExt::into_pidfd
209    fn create_pidfd(&mut self, val: bool) -> &mut process::Command;
210}
211
212impl CommandExt for process::Command {
213    fn create_pidfd(&mut self, val: bool) -> &mut process::Command {
214        self.as_inner_mut().create_pidfd(val);
215        self
216    }
217}