Skip to content

Commit

Permalink
optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
zidoshare committed Jul 31, 2021
1 parent c04a932 commit ea6f5f7
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions src/cgroups/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
env,
ffi::OsStr,
fmt::{Debug, Display},
fs::{self, File},
io::{BufRead, BufReader, Write},
Expand Down Expand Up @@ -174,16 +173,13 @@ pub fn create_cgroup_manager<P: Into<PathBuf>>(
pub fn get_all_pids(path: &Path) -> Result<Vec<Pid>> {
log::debug!("scan pids in folder: {:?}", path);
let mut result = vec![];
let proc_str = OsStr::new(CGROUP_PROCS);
walk_path(&path, &mut |p| {
let file_name = p.file_name();
if let Some(file_name) = file_name {
if file_name == proc_str {
let file = File::open(p)?;
for line in BufReader::new(file).lines() {
if let Ok(line) = line {
result.push(Pid::from_raw(line.parse::<i32>()?))
}
walk_dir(&path, &mut |p| {
let file_path = p.join(CGROUP_PROCS);
if file_path.exists() {
let file = File::open(file_path)?;
for line in BufReader::new(file).lines() {
if let Ok(line) = line {
result.push(Pid::from_raw(line.parse::<i32>()?))
}
}
}
Expand All @@ -192,18 +188,17 @@ pub fn get_all_pids(path: &Path) -> Result<Vec<Pid>> {
Ok(result)
}

fn walk_path<F>(path: &Path, c: &mut F) -> Result<()>
fn walk_dir<F>(path: &Path, c: &mut F) -> Result<()>
where
F: FnMut(&Path) -> Result<()>,
{
c(&path)?;
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();

if path.is_dir() {
walk_path(&path, c)?;
} else {
c(&path)?;
walk_dir(&path, c)?;
}
}
Ok(())
Expand Down

0 comments on commit ea6f5f7

Please sign in to comment.