Linux下获取CPU温度
不同架构的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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!