1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! An open handle on a process this process did not spawn — NO stdio (its pipes belong to its
//! real parent). The handle is opened from a `ProcessId`, never a bare pid, and every act through
//! it (`kill`, `terminate`, `wait*`, `graceful_shutdown`) reaches that process or reports it gone,
//! never a later holder of its pid. The tree acts (`kill_tree`, `terminate_tree`,
//! `graceful_shutdown_tree`) walk by identity and signal each member, through a handle opened by
//! its identity: a pidfd proved to name it on Linux, a process handle on Windows, an audit token on
//! macOS. The tree acts signal the root through this handle instead of a second open of it.
//! `wait()` is a death-watch, not an exit-status wait (see `Process::wait`). Its tree is
//! [`ProcessId::children`] and [`ProcessId::parent`].
use std::time::Duration;
use crate::error::Error;
use crate::identity::{Liveness, ProcessId, RawPid, Resolved};
use crate::os_process::{Exit, OsProcess};
#[path = "process/graceful.rs"]
mod graceful;
/// An open handle on a process, held since [`open`](Self::open). Acts through the handle
/// (`kill`, `terminate`, `wait*`, `graceful_shutdown`) reach this process or report it gone; never
/// a later holder of its pid. The tree acts (`kill_tree`, `terminate_tree`,
/// `graceful_shutdown_tree`) signal each member through a handle opened by its identity, and the
/// root through this handle. Not `Clone`: open the [`ProcessId`] again.
///
/// For a process you spawn, use a [`Child`](crate::Child); to keep a process's identity for a later
/// open, use a [`ProcessId`].
#[derive(Debug)]
pub struct Process {
id: ProcessId,
os: Box<dyn OsProcess>,
}
impl Process {
/// Open the process `id` names. `Ok(None)`: no process has this identity (it is fully gone, or
/// its pid now names another process). A process that has exited but is not yet reaped, or
/// whose handle someone else still holds, opens as `Some` and reads [`Liveness::Dead`].
///
/// # Errors
///
/// - [`Error::Unassessable`]: the process exists but cannot be opened or its identity
/// verified (access denied, a `/proc` that is not this pid namespace's).
/// - [`Error::Unsupported`]: the OS lacks the mechanism (on Linux, a refused `pidfd_open`).
/// - [`Error::NotThreadGroupLeader`]: on Linux, `id` names a live thread that is not its
/// process's leader.
/// - [`Error::Io`]: the open failed otherwise (on Linux a failed pidfd call: `pidfd_open`, the
/// pidfd's inode read, or its `poll`, named for the call below the `Io`). macOS opens no kqueue:
/// the first look at the process does ([`wait`](Self::wait)).
pub fn open(id: ProcessId) -> Result<Option<Process>, Error> {
Self::open_with(crate::identity::HostKernel, id)
}
/// [`open`](Self::open), re-verifying `id` through `kernel`. On macOS the handle owns `kernel`,
/// so it lives as long as the handle; Linux and Windows drop it once the open is done.
pub(crate) fn open_with<K: crate::identity::Kernel + Send + 'static>(
kernel: K,
id: ProcessId,
) -> Result<Option<Process>, Error> {
Ok(crate::os_process::open_with(kernel, id)
.map_err(crate::os_process::OpenFailure::into_open_error)?
.map(|os| Process { id, os }))
}
/// [`open`](Self::open) the process holding `pid` now. `Ok(None)` if no process has the pid;
/// an exited but unreaped one opens as for [`open`](Self::open). Errors as for `open`: a pid
/// whose identity cannot be read is an `Err`, not `Ok(None)`; usually [`Error::Unassessable`],
/// and on Linux a refused or failed pidfd call is [`Error::Unsupported`] or [`Error::Io`].
pub fn open_pid(pid: RawPid) -> Result<Option<Process>, Error> {
Self::open_pid_with(crate::identity::HostKernel, pid)
}
/// [`open_pid`](Self::open_pid), reading the pid's identity and opening it through `kernel`, as
/// [`open_with`](Self::open_with) does.
pub(crate) fn open_pid_with<K: crate::identity::Kernel + Send + 'static>(
kernel: K,
pid: RawPid,
) -> Result<Option<Process>, Error> {
match ProcessId::of_with(&kernel, pid) {
(Resolved::Found(id), _) => Process::open_with(kernel, id),
(Resolved::Gone, _) => Ok(None),
(Resolved::Unknown, cause) => {
// A pidfd call that failed is the open's own failure: a refusal is `Unsupported`
// naming the open, as for `open`.
#[cfg(target_os = "linux")]
if let Some(call) = cause.call() {
return Err(crate::os_process::linux::open::open_error(call));
}
Err(crate::identity::unqueryable(&format!("pid {pid}"), cause))
}
}
}
/// An open handle on this process itself. Errors as for [`open`](Self::open).
pub fn current() -> Result<Process, Error> {
Process::open(ProcessId::try_current()?).map(|p| p.expect("the current process is not gone from itself"))
}
/// The stable identity (`(pid, key)`).
pub fn id(&self) -> ProcessId {
self.id
}
/// Whether the process is still running (zombie-exclusive), read through the handle.
/// [`Liveness::Dead`] once it has exited, [`Liveness::Unknown`] when the look fails (on
/// Windows, a handle without `SYNCHRONIZE` on a process that has not exited).
pub fn is_alive(&self) -> Liveness {
match self.os.exited() {
Ok(Exit::Exited) => Liveness::Dead,
// The exit edge has fired but the process is not yet a zombie.
Ok(Exit::Running(_) | Exit::Recheck) => Liveness::Alive,
Err(e) => {
log::debug!(
"is_alive: reading the exit state of pid {} failed: {report}",
self.id.pid(),
report = crate::error::Report(&e)
);
Liveness::Unknown
}
}
}
/// Block until the process exits. Death-watch: returns `()`, not an
/// `ExitStatus` ([`Child::wait`](crate::Child::wait) returns one, as the parent). Non-reaping.
/// Returns at once for a process that has already exited. On macOS
/// "exited" is a zombie or gone: once this returns, [`ProcessId::is_alive`] never reads `Alive`.
/// `Err` only on a wait failure; on Windows, for a handle without `SYNCHRONIZE`, while the
/// process runs (`ERROR_ACCESS_DENIED`). On macOS the first look at the process (a wait, a
/// timed wait or [`is_alive`](Self::is_alive)) arms its exit watch, a kqueue, so a wait there
/// can also fail with [`Error::Io`] when the kqueue cannot be created or armed (`EMFILE`), or
/// [`Error::Unassessable`] when the process's unique id cannot be read.
pub fn wait(&self) -> Result<(), Error> {
let exited = crate::os_process::drive::exited_held(&*self.os, None)?;
debug_assert!(exited);
Ok(())
}
/// Block up to `timeout` for the process to exit. `Ok(true)` = exited; `Ok(false)` =
/// still alive at expiry. `Duration::ZERO` polls once. Errors as for [`wait`](Self::wait).
pub fn wait_timeout(&self, timeout: Duration) -> Result<bool, Error> {
crate::os_process::drive::exited_held(&*self.os, Some(timeout))
}
/// Hard-kill the process (`SIGKILL` / `TerminateProcess`). Already-dead ⇒ `Ok`; a real
/// failure (no rights / `EPERM` / access-denied on a live process) ⇒ `Err`.
/// A process that reused the pid is never signalled, by a different mechanism per OS:
/// Linux uses `pidfd_send_signal` on the pidfd opened with this handle and Windows pins the
/// kernel object via its handle. macOS (14.4 and later) has no pidfd; it signals with
/// `proc_signal_with_audittoken` (the pid plus the process's `p_idversion`, which `exec`
/// changes), and the kernel checks the version while it holds a reference to the process.
/// The one residual there: `p_idversion` is 32 bits, so it matches a different process only
/// if it wrapped by a multiple of 2^32 between the read and the call while the pid was
/// reused.
pub fn kill(&self) -> Result<(), Error> {
crate::os_process::kill(&*self.os)
}
/// The held OS process, for the async wrapper.
#[cfg(feature = "tokio")]
pub(crate) fn os(&self) -> &dyn OsProcess {
&*self.os
}
}
/// The root of a tree walk that signals it through this handle. Never reaped by this handle, so
/// nothing is sent by its pid on its word ([`RootState::unheld`](crate::signal::RootState::unheld)).
impl crate::containment::Root for Process {
fn pid(&self) -> u32 {
self.id.pid()
}
fn signal(&self, sig: crate::signal::Sig) -> Result<crate::signal::Sent, Error> {
self.os.signal(sig)
}
#[cfg(unix)]
fn state(&self) -> crate::signal::RootState {
crate::signal::RootState::unheld()
}
#[cfg(target_os = "linux")]
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
Some(self.os.os_handle())
}
}
#[cfg(test)]
#[path = "process_tests.rs"]
mod process_tests;