Я читаю файл ядра /proc/stat
, используя ifstream:
std::ifstream proc_stat_file("/proc/stat", std::ifstream::in);
Этот файл содержит время загрузки ЦП для различных процессов и часто обновляется ядром. Я пишу приложение, которое должно регистрировать общее время процессора при разборе этого файла каждую секунду. Я открыл файл один раз, используя 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
между вызовами. Я не уверен почему. Есть идеи?