kata-containers / cgroups-rs

Native Rust library for managing control groups under Linux
https://crates.io/crates/cgroups-rs
Other
116 stars 47 forks source link

read tasks hang when the cgroup dir removed after open #62

Closed quanweiZhou closed 2 years ago

quanweiZhou commented 2 years ago

Describe the bug read tasks hang when the cgroup dir removed after open

Expected behavior should not hang

Additional context current behavior

      /// Get the list of tasks that this controller has.
      fn tasks(&self) -> Vec<CgroupPid> {
          let mut file = "tasks";
          if self.is_v2() {
              file = "cgroup.procs";
          }
          self.open_path(file, false)
              .map(|file| {
                  let bf = BufReader::new(file);
                  let mut v = Vec::new();
                  for line in bf.lines().flatten() {
                      let n = line.trim().parse().unwrap_or(0u64);
                      v.push(n);
                  }
                  v.into_iter().map(CgroupPid::from).collect()
              })
              .unwrap_or_default()
      }

if the group dir remove after open_path the bf.lines() will return Some(Err(...)). when for line in "bf.lines().flatten()" will hang, because the reader will return an error and the flatten always in the loop

here is the simulation program: after running this demo, will always hang

use std::io::{BufRead, BufReader};

fn main() {
    let dir = "/sys/fs/cgroup/cpuset,cpu,cpuacct/line_test";
    let file_path = format!("{}/tasks", dir);

    // create dir
    std::fs::create_dir_all(dir).unwrap();

    let file = std::fs::File::open(&file_path).unwrap();

    std::fs::remove_dir(dir).unwrap();

    let bf = BufReader::new(file);
    for line in bf.lines().flatten() {
        println!("line: {}", line);
    }

    println!("end");
}