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