SystemMaybe Fs::readDirFromDIR()

in src/oomd/util/Fs.cpp [124:162]


SystemMaybe<Fs::DirEnts> Fs::readDirFromDIR(DIR* d, int flags) {
  Fs::DirEnts de;

  while (struct dirent* dir = ::readdir(d)) {
    if (dir->d_name[0] == '.') {
      continue;
    }

    /*
     * Optimisation: Avoid doing lstat calls if kernfs gives us back d_type.
     * This actually can be pretty useful, since avoiding lstat()ing everything
     * can reduce oomd CPU usage by ~10% on a reasonably sized cgroup
     * hierarchy.
     */
    if ((flags & DirEntFlags::DE_FILE) && dir->d_type == DT_REG) {
      de.files.push_back(dir->d_name);
      continue;
    }
    if ((flags & DirEntFlags::DE_DIR) && dir->d_type == DT_DIR) {
      de.dirs.push_back(dir->d_name);
      continue;
    }

    struct stat buf;
    int ret = ::fstatat(dirfd(d), dir->d_name, &buf, AT_SYMLINK_NOFOLLOW);
    if (ret == -1) {
      return SYSTEM_ERROR(errno);
    }

    if ((flags & DirEntFlags::DE_FILE) && (buf.st_mode & S_IFREG)) {
      de.files.push_back(dir->d_name);
    }
    if ((flags & DirEntFlags::DE_DIR) && (buf.st_mode & S_IFDIR)) {
      de.files.push_back(dir->d_name);
    }
  }

  return de;
}