我正在使用ifstream读取内核文件/proc/stat
:
std::ifstream proc_stat_file("/proc/stat", std::ifstream::in);
此文件包含不同进程的CPU使用时间,并且经常被内核更新。我正在编写一个应用,该应用需要记录每秒分析此文件的总CPU时间。我已经在类的构造函数中使用ifstream
打开了文件。我正在尝试在该类的成员函数中读取文件内容:
void read_cpu_times()
{
std::string line;
const std::string cpu_string("cpu");
const std::size_t cpu_string_len = cpu_string.size();
while (std::getline(proc_stat_file, line)) {
// cpu stats line found
if (!line.compare(0, cpu_string_len, cpu_string)) {
std::istringstream ss(line);
// store entry
m_entries.emplace_back(cpu_info_obj());
cpu_info_obj & entry = m_entries.back();
// read cpu label
ss >> entry.cpu_label;
// count the number of cpu cores
if (entry.cpu_label.size() > cpu_string_len) {
++m_cpu_cores;
}
// read times
for (uint8_t i = 0U; i < static_cast<uint8_t>(CpuTimeState::CPU_TIME_STATES_NUM); ++i) {
ss >> entry.cpu_time_array[i];
}
}
}
// compute cpu total time
// Guest and Guest_nice are not included in the total time calculation since, they are
// already accounted in user and nice.
m_cpu_total_time = (m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_USER)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_NICE)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_SYSTEM)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IDLE)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IOWAIT)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IRQ)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_SOFTIRQ)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_STEAL)]);
//Reset the eof file flag and move file pointer to beginning for next read
//proc_stat_file.
proc_stat_file.clear();
proc_stat_file.seekg(0, std::ifstream::beg);
此read_cpu_times()
函数每秒被调用一次。但是两次调用之间我没有得到m_cpu_total_time
的更新值。我不知道为什么。有什么想法吗?
我能够解决我的问题。文件内容正在更新,但是每次读取文件后我都没有清除m_entries
向量。因此,它始终从向量m_entries
的第一个元素开始读取,因为这是从未被清除的第一次读取的数据。