From d7e29edd026caca2f6d95a61eea8b7d9d7050c9c Mon Sep 17 00:00:00 2001 From: Paul Pan Date: Wed, 13 Mar 2024 19:05:30 +0800 Subject: [PATCH] fix: force clear stream state introduced by rdbuf --- cgroup2.cc | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/cgroup2.cc b/cgroup2.cc index 97504a9..b1c76e3 100644 --- a/cgroup2.cc +++ b/cgroup2.cc @@ -280,30 +280,41 @@ void dumpCgroupStats(nsjconf_t *nsjconf, const std::string &cgroup_path) { return; } + auto res_name = [&](const std::string &res) -> std::string { + return cgroup_path + "/" + res; + }; + auto get_length = [&](std::ifstream &f) -> size_t { + f.seekg(0, std::ios::end); + auto sz = f.tellg(); + f.seekg(0, std::ios::beg); + return sz; + }; + const auto stats = {"cpu.stat", "io.stat", "memory.stat"}; for (const auto &res : stats) { - std::ifstream f(cgroup_path + "/" + res); + auto path = res_name(res); + std::ifstream f(path); if (!f.is_open()) { - PLOG_W("Failed to open cgroup resource file '%s'", - (cgroup_path + "/" + res).c_str()); + PLOG_W("Invalid cgroup resource file '%s'", path.c_str()); continue; } - dump_file << f.rdbuf(); - dump_file << std::endl; + dump_file << f.rdbuf() << std::endl; + dump_file.clear(); f.close(); } const auto mem_stats = {"memory.peak", "memory.swap.peak"}; for (const auto &res : mem_stats) { - std::ifstream f(cgroup_path + "/" + res); + auto path = res_name(res); + std::ifstream f(path); if (!f.is_open()) { - PLOG_W("Failed to open cgroup resource file '%s'", - (cgroup_path + "/" + res).c_str()); + PLOG_W("Invalid cgroup resource file '%s'", path.c_str()); continue; } std::string line; std::getline(f, line); dump_file << res << ' ' << line << std::endl; + dump_file.clear(); f.close(); }