Linux下获取CPU温度

发布时间 2023-12-01 10:44:24作者: umichan

不同架构的CPU,CPU温度所在的系统文件有区别
CPU温度相关的系统文件位于

cd /sys/class/thermal

可以看到文件夹下有很多命名为thermal_zone{n}的文件夹
以thermal_zone0文件夹为例

cat /sys/class/thermal/thermal_zone0/type

可以获取到thermal_zone0设备的类型
对x86架构的CPU,type应为x86_pkg_temp;而arm架构的CPU,type为CPU-therm
对thermal_zone0到thermal_zone{n}文件夹遍历,找到对应的文件夹
以thermal_zone0文件夹为例

cat /sys/class/thermal/thermal_zone0/temp

可以获取到当前设备的温度

C++实现

#include <string>
#include <fstream>
#include <iostream>

class CpuMonitor {
public:
    double GetTemperature() {
        if (cpu_temp_fs_.is_open()) {
            std::string buf;
            cpu_temp_fs_ >> buf;
            cpu_temp_fs_.seekg(0);

            try {
                double temperature = std::stoi(buf) / 10;
                temperature /= 100;
                return temperature;
            } catch (...) {
            }
        }
        double temperature = -1.0;
        for (int i = 0; temperature < 0; ++i) {
            temperature = GetTemperature(i);
            if (temperature == -2.0) {
                return -1.0;
            }
        }
        return temperature;
    }

private:
    double GetTemperature(int n) {
        std::string path = "/sys/class/thermal/thermal_zone" + std::to_string(n);
        std::fstream f;
        f.open(path + "/type", std::ios::in);
        if (!f.good()) {
            return -2.0;
        }
        std::string buf;
        f >> buf;
        f.seekg(0);
#ifdef __aarch64__
        std::string type = "CPU-therm";
#else
        std::string type = "x86_pkg_temp";
#endif
        if (type != buf) {
            return -1.0;
        }
        cpu_temp_fs_.open(path + "/temp", std::ios::in);
        cpu_temp_fs_ >> buf;
        cpu_temp_fs_.seekg(0);

        try {
            double temperature = std::stoi(buf) / 10;
            temperature /= 100;
            return temperature;
        } catch (...) {
        }
        return -1.0;
    }

private:
    std::fstream cpu_temp_fs_;
};

int main() {
    CpuMonitor m;
    std::cout << m.GetTemperature() << "\n";
    return 0;
}