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