Skip to content

Commit

Permalink
Merge pull request prometheus#56 from edigaryev/process-custom-procfs…
Browse files Browse the repository at this point in the history
…-root

Introduce Process::new_with_root() constructor
  • Loading branch information
eminence authored Dec 17, 2019
2 parents 7267c76 + 2471e45 commit 25d97d8
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions src/process.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
//! Functions and structs related to process information
//!
//! The primary source of data for functions in this module is the files in a /proc/<pid>/
//! directory. If you have a process id, you can use
//! The primary source of data for functions in this module is the files in a `/proc/<pid>/`
//! directory. If you have a process ID, you can use
//! [`Process::new(pid)`](struct.Process.html#method.new), otherwise you can get a
//! list of all running processes using [`all_processes()`](fn.all_processes.html).
//!
//! In case you have procfs filesystem mounted to a location other than `/proc`,
//! use [`Process::new_with_root()`](struct.Process.html#method.new_with_root).
//!
//! # Examples
//!
//! Here's a small example that prints out all processes that are running on the same tty as the calling
Expand Down Expand Up @@ -1670,18 +1673,23 @@ pub struct Process {
}

impl Process {
/// Tries to create a `Process` based on a PID.
/// Returns a `Process` based on a specified PID.
///
/// This can fail if the process doesn't exist, or if you don't have permission to access it.
pub fn new(pid: pid_t) -> ProcResult<Process> {
let root = PathBuf::from("/proc").join(format!("{}", pid));
Self::new_with_root(root)
}

/// Returns a `Process` based on a specified `/proc/<pid>` path.
pub fn new_with_root(root: PathBuf) -> ProcResult<Process> {
let path = root.join("stat");
let stat = Stat::from_reader(FileWrapper::open(&path)?)?;

let md = std::fs::metadata(&root)?;

Ok(Process {
pid,
pid: stat.pid,
root,
stat,
owner: md.st_uid(),
Expand All @@ -1693,16 +1701,7 @@ impl Process {
/// This is done by using the `/proc/self` symlink
pub fn myself() -> ProcResult<Process> {
let root = PathBuf::from("/proc/self");
let path = root.join("stat");
let stat = Stat::from_reader(FileWrapper::open(&path)?)?;
let md = std::fs::metadata(&root)?;

Ok(Process {
pid: stat.pid,
root,
stat,
owner: md.st_uid(),
})
Self::new_with_root(root)
}

/// Returns the complete command line for the process, unless the process is a zombie.
Expand Down

0 comments on commit 25d97d8

Please sign in to comment.