| 1 |
//! Functions and structs related to process information |
| 2 |
//! |
| 3 |
//! The primary source of data for functions in this module is the files in a `/proc/<pid>/` |
| 4 |
//! directory. If you have a process ID, you can use |
| 5 |
//! [`Process::new(pid)`](struct.Process.html#method.new), otherwise you can get a |
| 6 |
//! list of all running processes using [`all_processes()`](fn.all_processes.html). |
| 7 |
//! |
| 8 |
//! In case you have procfs filesystem mounted to a location other than `/proc`, |
| 9 |
//! use [`Process::new_with_root()`](struct.Process.html#method.new_with_root). |
| 10 |
//! |
| 11 |
//! # Examples |
| 12 |
//! |
| 13 |
//! Here's a small example that prints out all processes that are running on the same tty as the calling |
| 14 |
//! process. This is very similar to what "ps" does in its default mode. You can run this example |
| 15 |
//! yourself with: |
| 16 |
//! |
| 17 |
//! > cargo run --example=ps |
| 18 |
//! |
| 19 |
//! ```rust |
| 20 |
//! let me = procfs::process::Process::myself().unwrap(); |
| 21 |
//! let me_stat = me.stat().unwrap(); |
| 22 |
//! let tps = procfs::ticks_per_second(); |
| 23 |
//! |
| 24 |
//! println!("{: >10} {: <8} {: >8} {}", "PID", "TTY", "TIME", "CMD"); |
| 25 |
//! |
| 26 |
//! let tty = format!("pty/{}", me_stat.tty_nr().1); |
| 27 |
//! for prc in procfs::process::all_processes().unwrap() { |
| 28 |
//! let Ok(prc) = prc else { |
| 29 |
//! // process vanished |
| 30 |
//! continue; |
| 31 |
//! }; |
| 32 |
//! let Ok(stat) = prc.stat() else { |
| 33 |
//! // process vanished |
| 34 |
//! continue; |
| 35 |
//! }; |
| 36 |
//! if let Ok(stat) = prc.stat() { |
| 37 |
//! if stat.tty_nr == me_stat.tty_nr { |
| 38 |
//! // total_time is in seconds |
| 39 |
//! let total_time = |
| 40 |
//! (stat.utime + stat.stime) as f32 / (tps as f32); |
| 41 |
//! println!( |
| 42 |
//! "{: >10} {: <8} {: >8} {}", |
| 43 |
//! stat.pid, tty, total_time, stat.comm |
| 44 |
//! ); |
| 45 |
//! } |
| 46 |
//! } |
| 47 |
//! } |
| 48 |
//! ``` |
| 49 |
//! |
| 50 |
//! Here's a simple example of how you could get the total memory used by the current process. |
| 51 |
//! There are several ways to do this. For a longer example, see the `examples/self_memory.rs` |
| 52 |
//! file in the git repository. You can run this example with: |
| 53 |
//! |
| 54 |
//! > cargo run --example=self_memory |
| 55 |
//! |
| 56 |
//! ```rust |
| 57 |
//! # use procfs::process::Process; |
| 58 |
//! let me = Process::myself().unwrap(); |
| 59 |
//! let me_stat = me.stat().unwrap(); |
| 60 |
//! let page_size = procfs::page_size(); |
| 61 |
//! |
| 62 |
//! println!("== Data from /proc/self/stat:"); |
| 63 |
//! println!("Total virtual memory used: {} bytes", me_stat.vsize); |
| 64 |
//! println!("Total resident set: {} pages ({} bytes)", me_stat.rss, me_stat.rss as u64 * page_size); |
| 65 |
//! ``` |
| 66 |
|
| 67 |
use super::*; |
| 68 |
use crate::net::{TcpNetEntry, UdpNetEntry}; |
| 69 |
use crate::sys::kernel::Version; |
| 70 |
|
| 71 |
pub use procfs_core::process::*; |
| 72 |
use rustix::fd::{AsFd, BorrowedFd, OwnedFd, RawFd}; |
| 73 |
use rustix::fs::{AtFlags, Mode, OFlags, RawMode}; |
| 74 |
#[cfg(feature = "serde1")] |
| 75 |
use serde::{Deserialize, Serialize}; |
| 76 |
use std::ffi::OsStr; |
| 77 |
use std::ffi::OsString; |
| 78 |
use std::fs::read_link; |
| 79 |
use std::io::{self, Read}; |
| 80 |
use std::os::unix::ffi::OsStringExt; |
| 81 |
use std::os::unix::fs::MetadataExt; |
| 82 |
use std::path::PathBuf; |
| 83 |
use std::str::FromStr; |
| 84 |
|
| 85 |
mod namespaces; |
| 86 |
|
| 87 |
mod task; |
| 88 |
pub use task::*; |
| 89 |
|
| 90 |
mod pagemap; |
| 91 |
pub use pagemap::*; |
| 92 |
|
| 93 |
#[cfg(test)] |
| 94 |
mod tests; |
| 95 |
|
| 96 |
bitflags! { |
| 97 |
/// The mode (read/write permissions) for an open file descriptor |
| 98 |
/// |
| 99 |
/// This is represented as `u16` since the values of these bits are |
| 100 |
/// [documented] to be within the `u16` range. |
| 101 |
/// |
| 102 |
/// [documented]: https://man7.org/linux/man-pages/man2/chmod.2.html#DESCRIPTION |
| 103 |
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))] |
| 104 |
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)] |
| 105 |
pub struct FDPermissions: u16 { |
| 106 |
const READ = Mode::RUSR.bits() as u16; |
| 107 |
const WRITE = Mode::WUSR.bits() as u16; |
| 108 |
const EXECUTE = Mode::XUSR.bits() as u16; |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
/// See the [Process::fd()] method |
| 113 |
#[derive(Clone)] |
| 114 |
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))] |
| 115 |
pub struct FDInfo { |
| 116 |
/// The file descriptor |
| 117 |
pub fd: i32, |
| 118 |
/// The permission bits for this FD |
| 119 |
/// |
| 120 |
/// **Note**: this field is only the owner read/write/execute bits. All the other bits |
| 121 |
/// (include filetype bits) are masked out. See also the `mode()` method. |
| 122 |
pub mode: u16, |
| 123 |
pub target: FDTarget, |
| 124 |
} |
| 125 |
|
| 126 |
impl FDInfo { |
| 127 |
/// Gets a file descriptor from a raw fd |
| 128 |
pub fn from_raw_fd(pid: i32, raw_fd: i32) -> ProcResult<Self> { |
| 129 |
Self::from_raw_fd_with_root("/proc", pid, raw_fd) |
| 130 |
} |
| 131 |
|
| 132 |
/// Gets a file descriptor from a raw fd based on a specified `/proc` path |
| 133 |
pub fn from_raw_fd_with_root(root: impl AsRef<Path>, pid: i32, raw_fd: i32) -> ProcResult<Self> { |
| 134 |
let path = root.as_ref().join(pid.to_string()).join("fd").join(raw_fd.to_string()); |
| 135 |
let link = wrap_io_error!(path, read_link(&path))?; |
| 136 |
let md = wrap_io_error!(path, path.symlink_metadata())?; |
| 137 |
let link_os: &OsStr = link.as_ref(); |
| 138 |
Ok(Self { |
| 139 |
fd: raw_fd, |
| 140 |
mode: ((md.mode() as RawMode) & Mode::RWXU.bits()) as u16, |
| 141 |
target: expect!(FDTarget::from_str(expect!(link_os.to_str()))), |
| 142 |
}) |
| 143 |
} |
| 144 |
|
| 145 |
/// Gets a file descriptor from a directory fd and a path relative to it. |
| 146 |
/// |
| 147 |
/// `base` is the path to the directory fd, and is used for error messages. |
| 148 |
fn from_process_at<P: AsRef<Path>, Q: AsRef<Path>>( |
| 149 |
base: P, |
| 150 |
dirfd: BorrowedFd, |
| 151 |
path: Q, |
| 152 |
fd: i32, |
| 153 |
) -> ProcResult<Self> { |
| 154 |
let p = path.as_ref(); |
| 155 |
let root = base.as_ref().join(p); |
| 156 |
// for 2.6.39 <= kernel < 3.6 fstat doesn't support O_PATH see https://github.com/eminence/procfs/issues/265 |
| 157 |
let flags = match Version::cached() { |
| 158 |
Ok(v) if v < KernelVersion::new(3, 6, 0) => OFlags::NOFOLLOW | OFlags::CLOEXEC, |
| 159 |
Ok(_) => OFlags::NOFOLLOW | OFlags::PATH | OFlags::CLOEXEC, |
| 160 |
Err(_) => OFlags::NOFOLLOW | OFlags::PATH | OFlags::CLOEXEC, |
| 161 |
}; |
| 162 |
let file = wrap_io_error!(root, rustix::fs::openat(dirfd, p, flags, Mode::empty()))?; |
| 163 |
let link = rustix::fs::readlinkat(&file, "", Vec::new()).map_err(io::Error::from)?; |
| 164 |
let md = |
| 165 |
rustix::fs::statat(&file, "", AtFlags::SYMLINK_NOFOLLOW | AtFlags::EMPTY_PATH).map_err(io::Error::from)?; |
| 166 |
|
| 167 |
let link_os = link.to_string_lossy(); |
| 168 |
let target = FDTarget::from_str(link_os.as_ref())?; |
| 169 |
Ok(FDInfo { |
| 170 |
fd, |
| 171 |
mode: (md.st_mode & Mode::RWXU.bits()) as u16, |
| 172 |
target, |
| 173 |
}) |
| 174 |
} |
| 175 |
|
| 176 |
/// Gets the read/write mode of this file descriptor as a bitfield |
| 177 |
pub fn mode(&self) -> FDPermissions { |
| 178 |
FDPermissions::from_bits_truncate(self.mode) |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
impl std::fmt::Debug for FDInfo { |
| 183 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 184 |
write!( |
| 185 |
f, |
| 186 |
"FDInfo {{ fd: {:?}, mode: 0{:o}, target: {:?} }}", |
| 187 |
&self.fd, self.mode, self.target |
| 188 |
) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
/// Represents a process in `/proc/<pid>`. |
| 193 |
/// |
| 194 |
/// **Note** The `Process` struct holds an open file descriptor to its `/proc/<pid>` directory. |
| 195 |
/// This makes it possible to construct a `Process` object and then later call the various methods |
| 196 |
/// on it without a risk of inadvertently getting information from the wrong process (due to PID |
| 197 |
/// reuse). |
| 198 |
/// |
| 199 |
/// However the downside is that holding a lot of `Process` objects might cause the process to run |
| 200 |
/// out of file descriptors. |
| 201 |
/// |
| 202 |
/// For use cases that don't involve holding a lot of `Process` objects, no special handler is |
| 203 |
/// needed. But if you do hold a lot of these objects (for example if you're writing a `ps` |
| 204 |
/// or `top` -like program), you'll likely want to gather all of the necessary info from `Process` |
| 205 |
/// object into a new struct and then drop the `Process` object |
| 206 |
/// |
| 207 |
#[derive(Debug)] |
| 208 |
pub struct Process { |
| 209 |
fd: OwnedFd, |
| 210 |
pub pid: i32, |
| 211 |
pub(crate) root: PathBuf, |
| 212 |
} |
| 213 |
|
| 214 |
/// Methods for constructing a new `Process` object. |
| 215 |
impl Process { |
| 216 |
/// Returns a `Process` based on a specified PID. |
| 217 |
/// |
| 218 |
/// This can fail if the process doesn't exist, or if you don't have permission to access it. |
| 219 |
pub fn new(pid: i32) -> ProcResult<Process> { |
| 220 |
let root = PathBuf::from("/proc").join(pid.to_string()); |
| 221 |
Self::new_with_root(root) |
| 222 |
} |
| 223 |
|
| 224 |
/// Returns a `Process` based on a specified `/proc/<pid>` path. |
| 225 |
pub fn new_with_root(root: PathBuf) -> ProcResult<Process> { |
| 226 |
// for 2.6.39 <= kernel < 3.6 fstat doesn't support O_PATH see https://github.com/eminence/procfs/issues/265 |
| 227 |
let flags = match Version::cached() { |
| 228 |
Ok(v) if v < KernelVersion::new(3, 6, 0) => OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 229 |
Ok(_) => OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 230 |
Err(_) => OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 231 |
}; |
| 232 |
let file = wrap_io_error!(root, rustix::fs::openat(rustix::fs::CWD, &root, flags, Mode::empty()))?; |
| 233 |
|
| 234 |
let pidres = root |
| 235 |
.as_path() |
| 236 |
.components() |
| 237 |
.last() |
| 238 |
.and_then(|c| match c { |
| 239 |
std::path::Component::Normal(s) => Some(s), |
| 240 |
_ => None, |
| 241 |
}) |
| 242 |
.and_then(|s| s.to_string_lossy().parse::<i32>().ok()) |
| 243 |
.or_else(|| { |
| 244 |
rustix::fs::readlinkat(rustix::fs::CWD, &root, Vec::new()) |
| 245 |
.ok() |
| 246 |
.and_then(|s| s.to_string_lossy().parse::<i32>().ok()) |
| 247 |
}); |
| 248 |
let pid = match pidres { |
| 249 |
Some(pid) => pid, |
| 250 |
None => return Err(ProcError::NotFound(Some(root))), |
| 251 |
}; |
| 252 |
|
| 253 |
Ok(Process { fd: file, pid, root }) |
| 254 |
} |
| 255 |
|
| 256 |
/// Returns a `Process` for the currently running process. |
| 257 |
/// |
| 258 |
/// This is done by using the `/proc/self` symlink |
| 259 |
pub fn myself() -> ProcResult<Process> { |
| 260 |
let root = PathBuf::from("/proc/self"); |
| 261 |
Self::new_with_root(root) |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
impl Process { |
| 266 |
/// Returns the complete command line for the process, unless the process is a zombie. |
| 267 |
pub fn cmdline(&self) -> ProcResult<Vec<String>> { |
| 268 |
let mut buf = String::new(); |
| 269 |
let mut f = FileWrapper::open_at(&self.root, &self.fd, "cmdline")?; |
| 270 |
f.read_to_string(&mut buf)?; |
| 271 |
Ok(buf |
| 272 |
.split('\0') |
| 273 |
.filter_map(|s| if !s.is_empty() { Some(s.to_string()) } else { None }) |
| 274 |
.collect()) |
| 275 |
} |
| 276 |
|
| 277 |
/// Returns the process ID for this process, if the process was created from an ID. Otherwise |
| 278 |
/// use stat().pid. |
| 279 |
pub fn pid(&self) -> i32 { |
| 280 |
self.pid |
| 281 |
} |
| 282 |
|
| 283 |
/// Is this process still alive? |
| 284 |
/// |
| 285 |
/// Processes in the Zombie or Dead state are not considered alive. |
| 286 |
pub fn is_alive(&self) -> bool { |
| 287 |
if let Ok(stat) = self.stat() { |
| 288 |
stat.state != 'Z' && stat.state != 'X' |
| 289 |
} else { |
| 290 |
false |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
/// What user owns this process? |
| 295 |
pub fn uid(&self) -> ProcResult<u32> { |
| 296 |
Ok(self.metadata()?.st_uid) |
| 297 |
} |
| 298 |
|
| 299 |
fn metadata(&self) -> ProcResult<rustix::fs::Stat> { |
| 300 |
Ok(rustix::fs::fstat(&self.fd).map_err(io::Error::from)?) |
| 301 |
} |
| 302 |
|
| 303 |
/// Retrieves current working directory of the process by dereferencing `/proc/<pid>/cwd` symbolic link. |
| 304 |
/// |
| 305 |
/// This method has the following caveats: |
| 306 |
/// |
| 307 |
/// * if the pathname has been unlinked, the symbolic link will contain the string " (deleted)" |
| 308 |
/// appended to the original pathname |
| 309 |
/// |
| 310 |
/// * in a multithreaded process, the contents of this symbolic link are not available if the |
| 311 |
/// main thread has already terminated (typically by calling `pthread_exit(3)`) |
| 312 |
/// |
| 313 |
/// * permission to dereference or read this symbolic link is governed by a |
| 314 |
/// `ptrace(2)` access mode `PTRACE_MODE_READ_FSCREDS` check |
| 315 |
pub fn cwd(&self) -> ProcResult<PathBuf> { |
| 316 |
Ok(PathBuf::from(OsString::from_vec( |
| 317 |
wrap_io_error!( |
| 318 |
self.root.join("cwd"), |
| 319 |
rustix::fs::readlinkat(&self.fd, "cwd", Vec::new()) |
| 320 |
)? |
| 321 |
.into_bytes(), |
| 322 |
))) |
| 323 |
} |
| 324 |
|
| 325 |
/// Retrieves current root directory of the process by dereferencing `/proc/<pid>/root` symbolic link. |
| 326 |
/// |
| 327 |
/// This method has the following caveats: |
| 328 |
/// |
| 329 |
/// * if the pathname has been unlinked, the symbolic link will contain the string " (deleted)" |
| 330 |
/// appended to the original pathname |
| 331 |
/// |
| 332 |
/// * in a multithreaded process, the contents of this symbolic link are not available if the |
| 333 |
/// main thread has already terminated (typically by calling `pthread_exit(3)`) |
| 334 |
/// |
| 335 |
/// * permission to dereference or read this symbolic link is governed by a |
| 336 |
/// `ptrace(2)` access mode `PTRACE_MODE_READ_FSCREDS` check |
| 337 |
pub fn root(&self) -> ProcResult<PathBuf> { |
| 338 |
Ok(PathBuf::from(OsString::from_vec( |
| 339 |
wrap_io_error!( |
| 340 |
self.root.join("root"), |
| 341 |
rustix::fs::readlinkat(&self.fd, "root", Vec::new()) |
| 342 |
)? |
| 343 |
.into_bytes(), |
| 344 |
))) |
| 345 |
} |
| 346 |
|
| 347 |
/// Gets the current environment for the process. This is done by reading the |
| 348 |
/// `/proc/pid/environ` file. |
| 349 |
pub fn environ(&self) -> ProcResult<HashMap<OsString, OsString>> { |
| 350 |
use std::os::unix::ffi::OsStrExt; |
| 351 |
|
| 352 |
let mut map = HashMap::new(); |
| 353 |
|
| 354 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "environ")?; |
| 355 |
let mut buf = Vec::new(); |
| 356 |
file.read_to_end(&mut buf)?; |
| 357 |
|
| 358 |
for slice in buf.split(|b| *b == 0) { |
| 359 |
// slice will be in the form key=var, so split on the first equals sign |
| 360 |
let mut split = slice.splitn(2, |b| *b == b'='); |
| 361 |
if let (Some(k), Some(v)) = (split.next(), split.next()) { |
| 362 |
map.insert(OsStr::from_bytes(k).to_os_string(), OsStr::from_bytes(v).to_os_string()); |
| 363 |
}; |
| 364 |
//let env = OsStr::from_bytes(slice); |
| 365 |
} |
| 366 |
|
| 367 |
Ok(map) |
| 368 |
} |
| 369 |
|
| 370 |
/// Retrieves the actual path of the executed command by dereferencing `/proc/<pid>/exe` symbolic link. |
| 371 |
/// |
| 372 |
/// This method has the following caveats: |
| 373 |
/// |
| 374 |
/// * if the pathname has been unlinked, the symbolic link will contain the string " (deleted)" |
| 375 |
/// appended to the original pathname |
| 376 |
/// |
| 377 |
/// * in a multithreaded process, the contents of this symbolic link are not available if the |
| 378 |
/// main thread has already terminated (typically by calling `pthread_exit(3)`) |
| 379 |
/// |
| 380 |
/// * permission to dereference or read this symbolic link is governed by a |
| 381 |
/// `ptrace(2)` access mode `PTRACE_MODE_READ_FSCREDS` check |
| 382 |
pub fn exe(&self) -> ProcResult<PathBuf> { |
| 383 |
Ok(PathBuf::from(OsString::from_vec( |
| 384 |
wrap_io_error!( |
| 385 |
self.root.join("exe"), |
| 386 |
rustix::fs::readlinkat(&self.fd, "exe", Vec::new()) |
| 387 |
)? |
| 388 |
.into_bytes(), |
| 389 |
))) |
| 390 |
} |
| 391 |
|
| 392 |
/// Return the Io stats for this process, based on the `/proc/pid/io` file. |
| 393 |
/// |
| 394 |
/// (since kernel 2.6.20) |
| 395 |
pub fn io(&self) -> ProcResult<Io> { |
| 396 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, "io")?) |
| 397 |
} |
| 398 |
|
| 399 |
/// Return a list of the currently mapped memory regions and their access permissions, based on |
| 400 |
/// the `/proc/pid/maps` file. |
| 401 |
pub fn maps(&self) -> ProcResult<MemoryMaps> { |
| 402 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, "maps")?) |
| 403 |
} |
| 404 |
|
| 405 |
/// Returns a list of currently mapped memory regions and verbose information about them, |
| 406 |
/// such as memory consumption per mapping, based on the `/proc/pid/smaps` file. |
| 407 |
/// |
| 408 |
/// (since Linux 2.6.14 and requires CONFIG_PROG_PAGE_MONITOR) |
| 409 |
pub fn smaps(&self) -> ProcResult<MemoryMaps> { |
| 410 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, "smaps")?) |
| 411 |
} |
| 412 |
|
| 413 |
/// This is the sum of all the smaps data but it is much more performant to get it this way. |
| 414 |
/// |
| 415 |
/// Since 4.14 and requires CONFIG_PROC_PAGE_MONITOR. |
| 416 |
pub fn smaps_rollup(&self) -> ProcResult<SmapsRollup> { |
| 417 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, "smaps_rollup")?) |
| 418 |
} |
| 419 |
|
| 420 |
/// Returns the [MountStat] data for this process's mount namespace. |
| 421 |
pub fn mountstats(&self) -> ProcResult<MountStats> { |
| 422 |
self.read("mountstats") |
| 423 |
} |
| 424 |
|
| 425 |
/// Returns info about the mountpoints in this this process's mount namespace. |
| 426 |
/// |
| 427 |
/// This data is taken from the `/proc/[pid]/mountinfo` file |
| 428 |
/// |
| 429 |
/// # Example: |
| 430 |
/// |
| 431 |
/// ``` |
| 432 |
/// # use procfs::process::Process; |
| 433 |
/// let stats = Process::myself().unwrap().mountstats().unwrap(); |
| 434 |
/// |
| 435 |
/// for mount in stats { |
| 436 |
/// println!("{} mounted on {} wth type {}", |
| 437 |
/// mount.device.unwrap_or("??".to_owned()), |
| 438 |
/// mount.mount_point.display(), |
| 439 |
/// mount.fs |
| 440 |
/// ); |
| 441 |
/// } |
| 442 |
/// ``` |
| 443 |
/// |
| 444 |
/// (Since Linux 2.6.26) |
| 445 |
pub fn mountinfo(&self) -> ProcResult<MountInfos> { |
| 446 |
self.read("mountinfo") |
| 447 |
} |
| 448 |
|
| 449 |
/// Gets the number of open file descriptors for a process |
| 450 |
/// |
| 451 |
/// Calling this function is more efficient than calling `fd().unwrap().count()` |
| 452 |
pub fn fd_count(&self) -> ProcResult<usize> { |
| 453 |
// Use fast path if available (Linux v6.2): https://github.com/torvalds/linux/commit/f1f1f2569901 |
| 454 |
let stat = wrap_io_error!( |
| 455 |
self.root.join("fd"), |
| 456 |
rustix::fs::statat(&self.fd, "fd", AtFlags::empty()) |
| 457 |
)?; |
| 458 |
if stat.st_size > 0 { |
| 459 |
return Ok(stat.st_size as usize); |
| 460 |
} |
| 461 |
|
| 462 |
let fds = wrap_io_error!( |
| 463 |
self.root.join("fd"), |
| 464 |
rustix::fs::openat( |
| 465 |
&self.fd, |
| 466 |
"fd", |
| 467 |
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 468 |
Mode::empty() |
| 469 |
) |
| 470 |
)?; |
| 471 |
let fds = wrap_io_error!(self.root.join("fd"), rustix::fs::Dir::read_from(fds))?; |
| 472 |
Ok(fds.count()) |
| 473 |
} |
| 474 |
|
| 475 |
/// Gets a iterator of open file descriptors for a process |
| 476 |
pub fn fd(&self) -> ProcResult<FDsIter> { |
| 477 |
let dir_fd = wrap_io_error!( |
| 478 |
self.root.join("fd"), |
| 479 |
rustix::fs::openat( |
| 480 |
&self.fd, |
| 481 |
"fd", |
| 482 |
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 483 |
Mode::empty() |
| 484 |
) |
| 485 |
)?; |
| 486 |
let dir = wrap_io_error!(self.root.join("fd"), rustix::fs::Dir::read_from(&dir_fd))?; |
| 487 |
Ok(FDsIter { |
| 488 |
inner: dir, |
| 489 |
inner_fd: dir_fd, |
| 490 |
root: self.root.clone(), |
| 491 |
}) |
| 492 |
} |
| 493 |
|
| 494 |
pub fn fd_from_fd(&self, fd: i32) -> ProcResult<FDInfo> { |
| 495 |
let path = PathBuf::from("fd").join(fd.to_string()); |
| 496 |
FDInfo::from_process_at(&self.root, self.fd.as_fd(), path, fd) |
| 497 |
} |
| 498 |
|
| 499 |
/// Lists which memory segments are written to the core dump in the event that a core dump is performed. |
| 500 |
/// |
| 501 |
/// By default, the following bits are set: |
| 502 |
/// 0, 1, 4 (if the CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS kernel configuration option is enabled), and 5. |
| 503 |
/// This default can be modified at boot time using the core dump_filter boot option. |
| 504 |
/// |
| 505 |
/// This function will return `Err(ProcError::NotFound)` if the `coredump_filter` file can't be |
| 506 |
/// found. If it returns `Ok(None)` then the process has no coredump_filter |
| 507 |
pub fn coredump_filter(&self) -> ProcResult<Option<CoredumpFlags>> { |
| 508 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "coredump_filter")?; |
| 509 |
let mut s = String::new(); |
| 510 |
file.read_to_string(&mut s)?; |
| 511 |
if s.trim().is_empty() { |
| 512 |
return Ok(None); |
| 513 |
} |
| 514 |
let flags = from_str!(u32, &s.trim(), 16, pid: self.pid); |
| 515 |
Ok(Some(expect!(CoredumpFlags::from_bits(flags)))) |
| 516 |
} |
| 517 |
|
| 518 |
/// Gets the process's autogroup membership |
| 519 |
/// |
| 520 |
/// (since Linux 2.6.38 and requires CONFIG_SCHED_AUTOGROUP) |
| 521 |
pub fn autogroup(&self) -> ProcResult<String> { |
| 522 |
let mut s = String::new(); |
| 523 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "autogroup")?; |
| 524 |
file.read_to_string(&mut s)?; |
| 525 |
Ok(s) |
| 526 |
} |
| 527 |
|
| 528 |
/// Get the process's auxiliary vector |
| 529 |
/// |
| 530 |
/// (since 2.6.0-test7) |
| 531 |
pub fn auxv(&self) -> ProcResult<HashMap<u64, u64>> { |
| 532 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "auxv")?; |
| 533 |
let mut map = HashMap::new(); |
| 534 |
|
| 535 |
let mut buf = Vec::new(); |
| 536 |
let bytes_read = file.read_to_end(&mut buf)?; |
| 537 |
if bytes_read == 0 { |
| 538 |
// some kernel processes won't have any data for their auxv file |
| 539 |
return Ok(map); |
| 540 |
} |
| 541 |
buf.truncate(bytes_read); |
| 542 |
let mut file = std::io::Cursor::new(buf); |
| 543 |
|
| 544 |
let mut buf = 0usize.to_ne_bytes(); |
| 545 |
loop { |
| 546 |
file.read_exact(&mut buf)?; |
| 547 |
let key = usize::from_ne_bytes(buf) as u64; |
| 548 |
file.read_exact(&mut buf)?; |
| 549 |
let value = usize::from_ne_bytes(buf) as u64; |
| 550 |
if key == 0 && value == 0 { |
| 551 |
break; |
| 552 |
} |
| 553 |
map.insert(key, value); |
| 554 |
} |
| 555 |
|
| 556 |
Ok(map) |
| 557 |
} |
| 558 |
|
| 559 |
/// Gets the symbolic name corresponding to the location in the kernel where the process is sleeping. |
| 560 |
/// |
| 561 |
/// (since Linux 2.6.0) |
| 562 |
pub fn wchan(&self) -> ProcResult<String> { |
| 563 |
let mut s = String::new(); |
| 564 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "wchan")?; |
| 565 |
file.read_to_string(&mut s)?; |
| 566 |
Ok(s) |
| 567 |
} |
| 568 |
|
| 569 |
/// Return the `Status` for this process, based on the `/proc/[pid]/status` file. |
| 570 |
pub fn status(&self) -> ProcResult<Status> { |
| 571 |
self.read("status") |
| 572 |
} |
| 573 |
|
| 574 |
/// Returns the status info from `/proc/[pid]/stat`. |
| 575 |
pub fn stat(&self) -> ProcResult<Stat> { |
| 576 |
self.read("stat") |
| 577 |
} |
| 578 |
|
| 579 |
/// Return the limits for this process |
| 580 |
pub fn limits(&self) -> ProcResult<Limits> { |
| 581 |
self.read("limits") |
| 582 |
} |
| 583 |
|
| 584 |
/// Gets the process' login uid. May not be available. |
| 585 |
pub fn loginuid(&self) -> ProcResult<u32> { |
| 586 |
let mut uid = String::new(); |
| 587 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "loginuid")?; |
| 588 |
file.read_to_string(&mut uid)?; |
| 589 |
Status::parse_uid_gid(&uid, 0) |
| 590 |
} |
| 591 |
|
| 592 |
/// The current score that the kernel gives to this process for the purpose of selecting a |
| 593 |
/// process for the OOM-killer |
| 594 |
/// |
| 595 |
/// A higher score means that the process is more likely to be selected by the OOM-killer. |
| 596 |
/// The basis for this score is the amount of memory used by the process, plus other factors. |
| 597 |
/// |
| 598 |
/// Values range from 0 (never kill) to 1000 (always kill) inclusive. |
| 599 |
/// |
| 600 |
/// (Since linux 2.6.11) |
| 601 |
pub fn oom_score(&self) -> ProcResult<u16> { |
| 602 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "oom_score")?; |
| 603 |
let mut oom = String::new(); |
| 604 |
file.read_to_string(&mut oom)?; |
| 605 |
Ok(from_str!(u16, oom.trim())) |
| 606 |
} |
| 607 |
|
| 608 |
/// Adjust score value is added to the oom score before choosing processes to kill. |
| 609 |
/// |
| 610 |
/// Values range from -1000 (never kill) to 1000 (always kill) inclusive. |
| 611 |
pub fn oom_score_adj(&self) -> ProcResult<i16> { |
| 612 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "oom_score_adj")?; |
| 613 |
let mut oom = String::new(); |
| 614 |
file.read_to_string(&mut oom)?; |
| 615 |
Ok(from_str!(i16, oom.trim())) |
| 616 |
} |
| 617 |
|
| 618 |
pub fn set_oom_score_adj(&self, new_oom_score_adj: i16) -> ProcResult<()> { |
| 619 |
let path = self.root.join("oom_score_adj"); |
| 620 |
write_value(path, new_oom_score_adj) |
| 621 |
} |
| 622 |
|
| 623 |
/// Set process memory information |
| 624 |
/// |
| 625 |
/// Much of this data is the same as the data from `stat()` and `status()` |
| 626 |
pub fn statm(&self) -> ProcResult<StatM> { |
| 627 |
self.read("statm") |
| 628 |
} |
| 629 |
|
| 630 |
/// Return a task for the main thread of this process |
| 631 |
pub fn task_main_thread(&self) -> ProcResult<Task> { |
| 632 |
self.task_from_tid(self.pid) |
| 633 |
} |
| 634 |
|
| 635 |
/// Return a task for the thread based on a specified TID |
| 636 |
pub fn task_from_tid(&self, tid: i32) -> ProcResult<Task> { |
| 637 |
let path = PathBuf::from("task").join(tid.to_string()); |
| 638 |
Task::from_process_at(&self.root, self.fd.as_fd(), path, self.pid, tid) |
| 639 |
} |
| 640 |
|
| 641 |
/// Return the `Schedstat` for this process, based on the `/proc/<pid>/schedstat` file. |
| 642 |
/// |
| 643 |
/// (Requires CONFIG_SCHED_INFO) |
| 644 |
pub fn schedstat(&self) -> ProcResult<Schedstat> { |
| 645 |
self.read("schedstat") |
| 646 |
} |
| 647 |
|
| 648 |
/// Returns the status info from `/proc/[pid]/syscall`. |
| 649 |
pub fn syscall(&self) -> ProcResult<Syscall> { |
| 650 |
self.read("syscall") |
| 651 |
} |
| 652 |
|
| 653 |
/// Iterate over all the [`Task`]s (aka Threads) in this process |
| 654 |
/// |
| 655 |
/// Note that the iterator does not receive a snapshot of tasks, it is a |
| 656 |
/// lazy iterator over whatever happens to be running when the iterator |
| 657 |
/// gets there, see the examples below. |
| 658 |
/// |
| 659 |
/// # Examples |
| 660 |
/// |
| 661 |
/// ## Simple iteration over subtasks |
| 662 |
/// |
| 663 |
/// If you want to get the info that most closely matches what was running |
| 664 |
/// when you call `tasks` you should collect them as quikcly as possible, |
| 665 |
/// and then run processing over that collection: |
| 666 |
/// |
| 667 |
/// ``` |
| 668 |
/// # use std::thread; |
| 669 |
/// # use std::sync::mpsc::channel; |
| 670 |
/// # use procfs::process::Process; |
| 671 |
/// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 672 |
/// # let (finish_tx, finish_rx) = channel(); |
| 673 |
/// # let (start_tx, start_rx) = channel(); |
| 674 |
/// let name = "testing:example"; |
| 675 |
/// let t = thread::Builder::new().name(name.to_string()) |
| 676 |
/// .spawn(move || { // do work |
| 677 |
/// # start_tx.send(()).unwrap(); |
| 678 |
/// # finish_rx.recv().expect("valid channel"); |
| 679 |
/// })?; |
| 680 |
/// # start_rx.recv()?; |
| 681 |
/// |
| 682 |
/// let proc = Process::myself()?; |
| 683 |
/// |
| 684 |
/// // Collect a snapshot |
| 685 |
/// let threads: Vec<_> = proc.tasks()?.flatten().map(|t| t.stat().unwrap().comm).collect(); |
| 686 |
/// threads.iter().find(|s| &**s == name).expect("thread should exist"); |
| 687 |
/// |
| 688 |
/// # finish_tx.send(()); |
| 689 |
/// # t.join().unwrap(); |
| 690 |
/// # Ok(()) |
| 691 |
/// # } |
| 692 |
/// ``` |
| 693 |
/// |
| 694 |
/// ## The TaskIterator is lazy |
| 695 |
/// |
| 696 |
/// This means both that tasks that stop before you get to them in |
| 697 |
/// iteration will not be there, and that new tasks that are created after |
| 698 |
/// you start the iterator *will* appear. |
| 699 |
/// |
| 700 |
/// ``` |
| 701 |
/// # use std::thread; |
| 702 |
/// # use std::sync::mpsc::channel; |
| 703 |
/// # use procfs::process::Process; |
| 704 |
/// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 705 |
/// let proc = Process::myself()?; |
| 706 |
/// |
| 707 |
/// // Task iteration is lazy |
| 708 |
/// let mut task_iter = proc.tasks()?.flatten().map(|t| t.stat().unwrap().comm); |
| 709 |
/// |
| 710 |
/// # let (finish_tx, finish_rx) = channel(); |
| 711 |
/// # let (start_tx, start_rx) = channel(); |
| 712 |
/// let name = "testing:lazy"; |
| 713 |
/// let t = thread::Builder::new().name(name.to_string()) |
| 714 |
/// .spawn(move || { // do work |
| 715 |
/// # start_tx.send(()).unwrap(); |
| 716 |
/// # finish_rx.recv().expect("valid channel"); |
| 717 |
/// })?; |
| 718 |
/// # start_rx.recv()?; |
| 719 |
/// |
| 720 |
/// task_iter.find(|s| &**s == name).expect("thread should exist"); |
| 721 |
/// |
| 722 |
/// # finish_tx.send(()); |
| 723 |
/// # t.join().unwrap(); |
| 724 |
/// # Ok(()) |
| 725 |
/// # } |
| 726 |
/// ``` |
| 727 |
/// |
| 728 |
/// Tasks that stop while you're iterating may or may not appear: |
| 729 |
/// |
| 730 |
/// ``` |
| 731 |
/// # use std::thread; |
| 732 |
/// # use std::sync::mpsc::channel; |
| 733 |
/// # use procfs::process::Process; |
| 734 |
/// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 735 |
/// # let (finish_tx, finish_rx) = channel(); |
| 736 |
/// # let (start_tx, start_rx) = channel(); |
| 737 |
/// let name = "testing:stopped"; |
| 738 |
/// let t = thread::Builder::new().name(name.to_string()) |
| 739 |
/// .spawn(move || { // do work |
| 740 |
/// # start_tx.send(()).unwrap(); |
| 741 |
/// # finish_rx.recv().expect("valid channel"); |
| 742 |
/// })?; |
| 743 |
/// # start_rx.recv()?; |
| 744 |
/// |
| 745 |
/// let proc = Process::myself()?; |
| 746 |
/// |
| 747 |
/// // Task iteration is lazy |
| 748 |
/// let mut task_iter = proc.tasks()?.flatten().map(|t| t.stat().unwrap().comm); |
| 749 |
/// |
| 750 |
/// # finish_tx.send(()); |
| 751 |
/// t.join().unwrap(); |
| 752 |
/// |
| 753 |
/// // It's impossible to know if this is going to be gone |
| 754 |
/// let _ = task_iter.find(|s| &**s == name).is_some(); |
| 755 |
/// # Ok(()) |
| 756 |
/// # } |
| 757 |
/// ``` |
| 758 |
pub fn tasks(&self) -> ProcResult<TasksIter> { |
| 759 |
let task_path = self.root.join("task"); |
| 760 |
let dir_fd = wrap_io_error!( |
| 761 |
&task_path, |
| 762 |
rustix::fs::openat( |
| 763 |
&self.fd, |
| 764 |
"task", |
| 765 |
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 766 |
Mode::empty() |
| 767 |
) |
| 768 |
)?; |
| 769 |
let dir = wrap_io_error!(&task_path, rustix::fs::Dir::read_from(&dir_fd))?; |
| 770 |
Ok(TasksIter { |
| 771 |
pid: self.pid, |
| 772 |
inner: dir, |
| 773 |
inner_fd: dir_fd, |
| 774 |
root: task_path, |
| 775 |
}) |
| 776 |
} |
| 777 |
|
| 778 |
/// Reads the tcp socket table from the process net namespace |
| 779 |
pub fn tcp(&self) -> ProcResult<Vec<TcpNetEntry>> { |
| 780 |
self.read_si("net/tcp").map(|net::TcpNetEntries(e)| e) |
| 781 |
} |
| 782 |
|
| 783 |
/// Reads the tcp6 socket table from the process net namespace |
| 784 |
pub fn tcp6(&self) -> ProcResult<Vec<TcpNetEntry>> { |
| 785 |
self.read_si("net/tcp6").map(|net::TcpNetEntries(e)| e) |
| 786 |
} |
| 787 |
|
| 788 |
/// Reads the udp socket table from the process net namespace |
| 789 |
pub fn udp(&self) -> ProcResult<Vec<UdpNetEntry>> { |
| 790 |
self.read_si("net/udp").map(|net::UdpNetEntries(e)| e) |
| 791 |
} |
| 792 |
|
| 793 |
/// Reads the udp6 socket table from the process net namespace |
| 794 |
pub fn udp6(&self) -> ProcResult<Vec<UdpNetEntry>> { |
| 795 |
self.read_si("net/udp6").map(|net::UdpNetEntries(e)| e) |
| 796 |
} |
| 797 |
|
| 798 |
/// Returns basic network device statistics for all interfaces in the process net namespace |
| 799 |
/// |
| 800 |
/// See also the [dev_status()](crate::net::dev_status()) function. |
| 801 |
pub fn dev_status(&self) -> ProcResult<HashMap<String, net::DeviceStatus>> { |
| 802 |
self.read("net/dev").map(|net::InterfaceDeviceStatus(e)| e) |
| 803 |
} |
| 804 |
|
| 805 |
/// Reads the unix socket table |
| 806 |
pub fn unix(&self) -> ProcResult<Vec<net::UnixNetEntry>> { |
| 807 |
self.read("net/unix").map(|net::UnixNetEntries(e)| e) |
| 808 |
} |
| 809 |
|
| 810 |
/// Reads the ARP table from the process net namespace |
| 811 |
pub fn arp(&self) -> ProcResult<Vec<net::ARPEntry>> { |
| 812 |
self.read("net/arp").map(|net::ArpEntries(e)| e) |
| 813 |
} |
| 814 |
|
| 815 |
/// Reads the ipv4 route table from the process net namespace |
| 816 |
pub fn route(&self) -> ProcResult<Vec<net::RouteEntry>> { |
| 817 |
self.read("net/route").map(|net::RouteEntries(e)| e) |
| 818 |
} |
| 819 |
|
| 820 |
/// Reads the network management information by Simple Network Management Protocol from the |
| 821 |
/// process net namespace |
| 822 |
pub fn snmp(&self) -> ProcResult<net::Snmp> { |
| 823 |
self.read("net/snmp") |
| 824 |
} |
| 825 |
|
| 826 |
/// Reads the network management information of IPv6 by Simple Network Management Protocol from |
| 827 |
/// the process net namespace |
| 828 |
pub fn snmp6(&self) -> ProcResult<net::Snmp6> { |
| 829 |
self.read("net/snmp6") |
| 830 |
} |
| 831 |
|
| 832 |
/// Opens a file to the process's memory (`/proc/<pid>/mem`). |
| 833 |
/// |
| 834 |
/// Note: you cannot start reading from the start of the file. You must first seek to |
| 835 |
/// a mapped page. See [Process::maps]. |
| 836 |
/// |
| 837 |
/// Permission to access this file is governed by a ptrace access mode PTRACE_MODE_ATTACH_FSCREDS check |
| 838 |
/// |
| 839 |
/// # Example |
| 840 |
/// |
| 841 |
/// Find the offset of the "hello" string in the process's stack, and compare it to the |
| 842 |
/// pointer of the variable containing "hello" |
| 843 |
/// |
| 844 |
/// ```rust |
| 845 |
/// # use std::io::{Read, Seek, SeekFrom}; |
| 846 |
/// # use procfs::process::{MMapPath, Process}; |
| 847 |
/// let me = Process::myself().unwrap(); |
| 848 |
/// let mut mem = me.mem().unwrap(); |
| 849 |
/// let maps = me.maps().unwrap(); |
| 850 |
/// |
| 851 |
/// let hello = "hello".to_string(); |
| 852 |
/// |
| 853 |
/// for map in maps { |
| 854 |
/// if map.pathname == MMapPath::Heap { |
| 855 |
/// mem.seek(SeekFrom::Start(map.address.0)).unwrap(); |
| 856 |
/// let mut buf = vec![0; (map.address.1 - map.address.0) as usize]; |
| 857 |
/// mem.read_exact(&mut buf).unwrap(); |
| 858 |
/// let idx = buf.windows(5).position(|p| p == b"hello").unwrap(); |
| 859 |
/// assert_eq!(map.address.0 + idx as u64, hello.as_ptr() as u64); |
| 860 |
/// } |
| 861 |
/// } |
| 862 |
/// ``` |
| 863 |
pub fn mem(&self) -> ProcResult<File> { |
| 864 |
let file = FileWrapper::open_at(&self.root, &self.fd, "mem")?; |
| 865 |
Ok(file.inner()) |
| 866 |
} |
| 867 |
|
| 868 |
/// Returns a file which is part of the process proc structure |
| 869 |
pub fn open_relative<P>(&self, path: P) -> ProcResult<File> |
| 870 |
where |
| 871 |
P: AsRef<Path>, |
| 872 |
{ |
| 873 |
let file = FileWrapper::open_at(&self.root, &self.fd, path)?; |
| 874 |
Ok(file.inner()) |
| 875 |
} |
| 876 |
|
| 877 |
/// Returns a file which is part of the process proc structure |
| 878 |
pub fn open_relative_flags<P>(&self, path: P, flags: OFlags) -> ProcResult<File> |
| 879 |
where |
| 880 |
P: AsRef<Path>, |
| 881 |
{ |
| 882 |
let file = FileWrapper::open_at_flags(&self.root, &self.fd, path, flags)?; |
| 883 |
Ok(file.inner()) |
| 884 |
} |
| 885 |
|
| 886 |
/// Parse a file relative to the process proc structure. |
| 887 |
pub fn read<P, T>(&self, path: P) -> ProcResult<T> |
| 888 |
where |
| 889 |
P: AsRef<Path>, |
| 890 |
T: FromRead, |
| 891 |
{ |
| 892 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, path)?) |
| 893 |
} |
| 894 |
|
| 895 |
/// Parse a file relative to the process proc structure. |
| 896 |
pub fn read_si<P, T>(&self, path: P) -> ProcResult<T> |
| 897 |
where |
| 898 |
P: AsRef<Path>, |
| 899 |
T: FromReadSI, |
| 900 |
{ |
| 901 |
FromReadSI::from_read( |
| 902 |
FileWrapper::open_at(&self.root, &self.fd, path)?, |
| 903 |
crate::current_system_info(), |
| 904 |
) |
| 905 |
} |
| 906 |
|
| 907 |
/// Clear reference bits |
| 908 |
/// |
| 909 |
/// See [ClearRefs] and [Process::pagemap()] |
| 910 |
pub fn clear_refs(&self, clear: ClearRefs) -> ProcResult<()> { |
| 911 |
write_value(self.root.join("clear_refs"), clear) |
| 912 |
} |
| 913 |
} |
| 914 |
|
| 915 |
/// The result of [`Process::fd`], iterates over all fds in a process |
| 916 |
#[derive(Debug)] |
| 917 |
pub struct FDsIter { |
| 918 |
inner: rustix::fs::Dir, |
| 919 |
inner_fd: rustix::fd::OwnedFd, |
| 920 |
root: PathBuf, |
| 921 |
} |
| 922 |
|
| 923 |
impl std::iter::Iterator for FDsIter { |
| 924 |
type Item = ProcResult<FDInfo>; |
| 925 |
fn next(&mut self) -> Option<ProcResult<FDInfo>> { |
| 926 |
loop { |
| 927 |
match self.inner.next() { |
| 928 |
Some(Ok(entry)) => { |
| 929 |
let name = entry.file_name().to_string_lossy(); |
| 930 |
if let Ok(fd) = RawFd::from_str(&name) { |
| 931 |
if let Ok(info) = FDInfo::from_process_at(&self.root, self.inner_fd.as_fd(), name.as_ref(), fd) |
| 932 |
{ |
| 933 |
break Some(Ok(info)); |
| 934 |
} |
| 935 |
} |
| 936 |
} |
| 937 |
Some(Err(e)) => break Some(Err(io::Error::from(e).into())), |
| 938 |
None => break None, |
| 939 |
} |
| 940 |
} |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
/// The result of [`Process::tasks`], iterates over all tasks in a process |
| 945 |
#[derive(Debug)] |
| 946 |
pub struct TasksIter { |
| 947 |
pid: i32, |
| 948 |
inner: rustix::fs::Dir, |
| 949 |
inner_fd: rustix::fd::OwnedFd, |
| 950 |
root: PathBuf, |
| 951 |
} |
| 952 |
|
| 953 |
impl std::iter::Iterator for TasksIter { |
| 954 |
type Item = ProcResult<Task>; |
| 955 |
fn next(&mut self) -> Option<ProcResult<Task>> { |
| 956 |
loop { |
| 957 |
match self.inner.next() { |
| 958 |
Some(Ok(tp)) => { |
| 959 |
if let Ok(tid) = i32::from_str(&tp.file_name().to_string_lossy()) { |
| 960 |
if let Ok(task) = |
| 961 |
Task::from_process_at(&self.root, self.inner_fd.as_fd(), tid.to_string(), self.pid, tid) |
| 962 |
{ |
| 963 |
break Some(Ok(task)); |
| 964 |
} |
| 965 |
} |
| 966 |
} |
| 967 |
Some(Err(e)) => break Some(Err(io::Error::from(e).into())), |
| 968 |
None => break None, |
| 969 |
} |
| 970 |
} |
| 971 |
} |
| 972 |
} |
| 973 |
|
| 974 |
/// Return a iterator of all processes |
| 975 |
/// |
| 976 |
/// If a process can't be constructed for some reason, it will be returned as an `Err(ProcError)` |
| 977 |
/// |
| 978 |
/// See also some important docs on the [ProcessesIter] struct. |
| 979 |
/// |
| 980 |
/// Error handling example |
| 981 |
/// ``` |
| 982 |
/// # use procfs::process::Process; |
| 983 |
/// let all_processes: Vec<Process> = procfs::process::all_processes() |
| 984 |
/// .expect("Can't read /proc") |
| 985 |
/// .filter_map(|p| match p { |
| 986 |
/// Ok(p) => Some(p), // happy path |
| 987 |
/// Err(e) => match e { |
| 988 |
/// procfs::ProcError::NotFound(_) => None, // process vanished during iteration, ignore it |
| 989 |
/// procfs::ProcError::Io(e, path) => None, // can match on path to decide if we can continue |
| 990 |
/// x => { |
| 991 |
/// println!("Can't read process due to error {x:?}"); // some unknown error |
| 992 |
/// None |
| 993 |
/// } |
| 994 |
/// }, |
| 995 |
/// }) |
| 996 |
/// .collect(); |
| 997 |
/// ``` |
| 998 |
pub fn all_processes() -> ProcResult<ProcessesIter> { |
| 999 |
all_processes_with_root("/proc") |
| 1000 |
} |
| 1001 |
|
| 1002 |
/// Return a list of all processes based on a specified `/proc` path |
| 1003 |
/// |
| 1004 |
/// See [all_processes] for details and examples |
| 1005 |
/// |
| 1006 |
/// See also some important docs on the [ProcessesIter] struct. |
| 1007 |
pub fn all_processes_with_root(root: impl AsRef<Path>) -> ProcResult<ProcessesIter> { |
| 1008 |
let root = root.as_ref(); |
| 1009 |
let dir = wrap_io_error!( |
| 1010 |
root, |
| 1011 |
rustix::fs::openat( |
| 1012 |
rustix::fs::CWD, |
| 1013 |
root, |
| 1014 |
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 1015 |
Mode::empty() |
| 1016 |
) |
| 1017 |
)?; |
| 1018 |
let dir = wrap_io_error!(root, rustix::fs::Dir::read_from(dir))?; |
| 1019 |
Ok(ProcessesIter { |
| 1020 |
root: PathBuf::from(root), |
| 1021 |
inner: dir, |
| 1022 |
}) |
| 1023 |
} |
| 1024 |
|
| 1025 |
/// An iterator over all processes in the system. |
| 1026 |
/// |
| 1027 |
/// **Note** This is a *lazy* iterator (like most iterators in rust). You will likely want to consume |
| 1028 |
/// this iterator as quickly as possible if you want a "snapshot" of the system (though it won't be a |
| 1029 |
/// true snapshot). Another important thing to keep in mind is that the [`Process`] struct holds an |
| 1030 |
/// open file descriptor to its corresponding `/proc/<pid>` directory. See the docs for [`Process`] |
| 1031 |
/// for more information. |
| 1032 |
#[derive(Debug)] |
| 1033 |
pub struct ProcessesIter { |
| 1034 |
root: PathBuf, |
| 1035 |
inner: rustix::fs::Dir, |
| 1036 |
} |
| 1037 |
|
| 1038 |
impl std::iter::Iterator for ProcessesIter { |
| 1039 |
type Item = ProcResult<Process>; |
| 1040 |
fn next(&mut self) -> Option<ProcResult<Process>> { |
| 1041 |
loop { |
| 1042 |
match self.inner.next() { |
| 1043 |
Some(Ok(entry)) => { |
| 1044 |
if let Ok(pid) = i32::from_str(&entry.file_name().to_string_lossy()) { |
| 1045 |
break Some(Process::new_with_root(self.root.join(pid.to_string()))); |
| 1046 |
} |
| 1047 |
} |
| 1048 |
Some(Err(e)) => break Some(Err(io::Error::from(e).into())), |
| 1049 |
None => break None, |
| 1050 |
} |
| 1051 |
} |
| 1052 |
} |
| 1053 |
} |