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