Skip to content

Commit 24db3f3

Browse files
committed
process: Add env_vars() method
1 parent 4cf06f7 commit 24db3f3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/uu/pgrep/src/process.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,19 @@ impl ProcessInformation {
491491
self.cached_thread_ids = Some(Rc::clone(&result));
492492
Rc::clone(&result)
493493
}
494+
495+
pub fn env_vars(&self) -> Result<HashMap<String, String>, io::Error> {
496+
let content = fs::read_to_string(format!("/proc/{}/environ", self.pid))?;
497+
498+
let mut env_vars = HashMap::new();
499+
for entry in content.split('\0') {
500+
if let Some((key, value)) = entry.split_once('=') {
501+
env_vars.insert(key.to_string(), value.to_string());
502+
}
503+
}
504+
505+
Ok(env_vars)
506+
}
494507
}
495508
impl TryFrom<DirEntry> for ProcessInformation {
496509
type Error = io::Error;
@@ -692,4 +705,16 @@ mod tests {
692705
}
693706
}
694707
}
708+
709+
#[test]
710+
#[cfg(target_os = "linux")]
711+
fn test_environ() {
712+
let pid_entry = ProcessInformation::current_process_info().unwrap();
713+
let env_vars = pid_entry.env_vars().unwrap();
714+
715+
assert_eq!(
716+
*env_vars.get("HOME").unwrap(),
717+
std::env::var("HOME").unwrap()
718+
);
719+
}
695720
}

0 commit comments

Comments
 (0)