开发者

Linux下如何使用C++获取硬件信息

目录
  • 方法
  • 获取CPU信息:读取"/proc/cpuinfo"文件
  • 获取磁盘信息:读取"/proc/diskstats"文件
  • 获取BIOS信息有两种方法
  • 获取主板信息有两种方法
  • 代码部分
  • 代码链接
  • 部分运行结果

方法

通过读取linux下存放硬件信息的文件来获取CPU、主板、磁盘、bios信息

获取CPU信息:读取"/proc/cpuinfo"文件

Linux下如何使用C++获取硬件信息

字段及其含义:

处理器基本信息:

  • processor:处理器的逻辑编号,从 0 开始,用于标识系统中的每个逻辑 CPU。
  • vendor_id:CPU制造商的标识符。例如,对于 Intel CPU,可能是GenuineIntel;对于 AMD CPU,可能是AuthenticAMD。

处理器型号与家族信息

  • cpu family:CPU 所属的家族编号。不同家族的 CPU 可能具有不同的架构和特性。例如,Intel 的酷睿系列和至强系列可能属于不同的家族。
  • model:CPU型号编号,结合cpu family可以更准确地确定 CPU 的具体型号。
  • model name:CPU 的完整型号名称,提供了详细的 CPU 型号描述,如Intel® Core™ i7-10700K CPU @ 3.80GHz。

步进与微代码信息:

  • stepping:CPU的步进编号,它标识了 CPU 的修订版本。不同的步进可能包含对之前版本的错误修复或性能改进。
  • microcode:CPU微代码版本号,微代码是嵌入在 CPU 中的一小段代码,用于协助 CPU 执行指令,可以通过更新微代码来修复 CPU 的一些问题或提升性能。

性能相关信息:

cpu MHz:CPU当前的运行频率,单位为 MHz。这可能是动态变化的,尤其是在支持节能技术(如 Intel 的 SpeedStep 或 AMD 的

  • Cool’n’Quiet)的 CPU 上。
  • cache size:CPU 缓存的大小,通常以 KB 或 MB 为单位。缓存可以提高 CPU 访问数据的速度,较大的缓存通常意味着更好的性能。

多处理器与多核信息:

  • physical id:物理处理器的标识符。在多处理器系统中,每个物理 CPU 有一个唯一的physical id。
  • siblings:同一物理 CPU上的逻辑处理器数量,即超线程技术下每个物理核心对应的逻辑核心数。例如,如果一个物理核心支持超线程,siblings可能为 2。
  • core id:每个物理核心的唯一标识符,在同一物理 CPU 内,不同的物理核心有不同的core id。
  • cpu cores:每个物理 CPU 中的核心数量,不包括超线程产生的逻辑核心。

其他信息:

  • apicid:高级可编程中断控制器(APIC)标识符,用于多处理器系统中的中断处理。
  • flags:CPU支持的特性标志列表,每个标志表示 CPU 支持的一种特定功能或指令集,如mmx、sse、sse2等,这些指令集可以加速特定类型的计算任务。
  • bogomips:代表 “BogusMIPS(伪每秒百万条指令数)”。它是一种对 CPU 性能的近似估计值,并非基于实际指令执行的精确测量。这个数值最初由 Linus Torvalds引入 Linux 内核,作为一种快速且相对简单的方法来评估 CPU 的处理能力。
  • clflush size:缓存行刷新(Cache Line Flush)操作所涉及的缓存行大小。

获取磁盘信息:读取"/proc/diskstats"文件

Linux下如何使用C++获取硬件信息

字段及其含义(从左至右):

  • 主设备号(Major device number):在示例中为8,它标识设备类型。例如,8通常代表SCSI 磁盘设备。不同的设备类型有不同的主设备号,可用于识别设备所属的大类。
  • 次设备号(Minor device number):示例中的0,它用于在同一主设备类型下进一步区分具体的设备实例。主设备号和次设备号共同唯一标识系统中的一个块设备。
  • 设备名称(Device name):这里是sda,这是设备在系统中的名称,通常对应/dev目录下的设备文件名,方便用户和系统管理员识别和操作具体设备。
  • 读完成次数(Reads completed successfully):212553,表示从设备成功完成的读操作次数。每次成功读取数据块,该计数增加。
  • 读合并次数(Reads merged):14992,系统有时会合并相邻的读请求以提高 I/O 效率,该字段统计了合并读操作的次数。合并读可以减少I/O 操作的总次数,提升性能。
  • 读扇区数(Sectors read):1469963,表示从设备读取的扇区总数。一个扇区通常是 512 字节(在现代设备中也可能是 4096字节等),这个数字反映了读取的数据量(以扇区为单位)。
  • 读操作花费的毫秒数(Time spent reading (ms)):334512,累计花费在读操作上的时间,以毫秒为单位。它反映了设备读取数据所花费的总时间,可用于评估读性能。
  • 写完成次数(Writes completed successfully):1005650,表示向设备成功完成的写操作次数。每次成功写入数据块,该计数增加。
  • 写合并次数(Writes merged):121259,类似于读合并,系统会合并相邻的写请求,该字段统计了合并写操作的次数,以提高写性能。
  • 写扇区数(Sectors written):6743707,表示向设备写入的扇区总数,反映了写入的数据量(以扇区为单位)。
  • 写操作花费的毫秒数(Time spent writing (ms)):10052256,累计花费在写操作上的时间,以毫秒为单位,可用于评估写性能。
  • 当前I/O 操作数(I/O requests currently in progress):0,表示当前正在进行的 I/O请求数量。如果这个值持续不为零,可能表示设备出现了 I/O 瓶颈。
  • I/O操作花费的总毫秒数(Time spent doing I/O (ms)):343049,累计花费在所有 I/O操作(读和写)上的时间,以毫秒为单位。
  • 加权的I/O 操作花费的毫秒数(Weighted time spent doing I/O (ms)):10386768,这是一个加权时间,考虑了I/O 请求的排队时间等因素,能更全面地反映 I/O 操作对系统资源的占用情况。

获取BIOS信息有两种方法

1.读取文件

可以通过读取三个文件分别获得BIOS供应商名称、BIOS版本号、BIOS发布日期,分别是:

BIOS供应商名称:/sys/class/dmi/id/bios_vendor

BIOS版本号:/sys/class/dmi/id/bios_version

BIOS发布日期:/sys/class/dmi/id/bios_date

优点:

无需 root 权限​​:普通用户即可访问。无额外依赖​​:直接通过文件接口读取,避免调用外部命令。​​适用于容器/虚拟化环境​​:即使 DMI 信息被限制,部分字段仍可能可用。

缺点:获取到的信息少。

2.使用dmidecode命令

工作方式:dmidecode的工作方式就是解析DMI表

命令:sudo dmidecode -t bios

Linux下如何使用C++获取硬件信息

字段含义:

  • Vendor:BIOS供应商名称
  • Version:BIOS版本号
  • Release Date:BIOS发布日期
  • Address:BIOS在内存中的物理地址(十六进制)
  • Runtime Size​:BIOS运行时占用的内存大小
  • ROM Size:存储 BIOS固件的 ROM(只读存储器)容量
  • Characteristics:BIOS支持的特性列表,每个特性对应一个硬件或软件功能
  • ​​BIOS Revision​:BIOS 的修订版本号(可能与 Version 不同)
  • Firmware Revision​:主板固件的版本号(可能与 BIOS 版本分离)

优点: 获取的信息更多、更全面。

缺点:​

  • 权限要求​​:dmidecode 需要 ​​root 权限​​ 才能读取完整 DMI表,如果运行程序的用户不是root用户会失败。
  • 依赖性​​:dmidecode方法需要安装该工具(通常默认已安装),常见的安装目录。有"/usr/sbin/dmidecode"、“/sbin/dmidecode”、“/usr/local/sbin/dmidecode”。代码在调用命令前需要先验证是否存在路径。
  • 适用性​​:虚拟化环境(如容器)中可能无法提供完整的DMI信息。

获取主板信息有两种方法

1.读取文件

可以通过读取文件分别获得主板供应商名称、主板版本号、主板型号,主板序列号,主板资产标签分别是:

主板供应商名称:/sys/class/dmi/id/board_vendor

主板版本号:/sys/class/dmi/id/board_version

主板型号:/sys/class/dmi/id/board_name

主板序列号:/sys/class/dmi/id/board_serial,读取该文件需要root权限,所以代码中无法依靠读取文件获取,但是可以通过dmidecode命令获取(见下文)

主板资产标签:/sys/class/dmi/id/board_asset_tag

优点:

无需 root 权限​​:普通用户即可访问。无额外依赖​​:直接通过文件接口读取,避免调用外部命令。​​适用于容器/虚拟化环境​​:即使 DMI 信息被限制,部分字段仍可能可用。

缺点: 获取到的信息少。

2.使用dmidecode命令

工作方式:dmidecode的工作方式就是解析DMI表

命令:sudo dmidecode -t baseboard

Linux下如何使用C++获取硬件信息

字段含义:

  • Manufacturer:主板制造商
  • Product Name: 主板型号
  • Version:主板版本号,None为未指定
  • Serial Number:主板序列号,None为未指定
  • Asset Tag: 资产标签,Not Specified为未指定
  • Features:主板特殊功能,None为无特殊功能
  • Location In Chassis:主板在机箱中的位置,Not Specified未记录
  • Chassis Handle:关联的机箱记录句柄,0x0000为未关联或默认值
  • Type:主板类型,Unknown为未明确
  • Contained Object Handle:关联的子设备,0表示无关联

优点: 获取的信息更多、更全面。

缺点:​

  • 权限要求​​:dmidecode 需要 ​​root 权限​​ 才能读取完整 DMI表,如果运行程序的用户不是root用户会失败。
  • 依赖性​​:dmidecode方法需要安装该工具(通常默认已安装),常见的安装目录。有"/usr/sbin/dmidecode"、“/sbin/dmidecode”、“/usr/local/sbin/dmidecode”。代码在调用命令前需要先验证是否存在路径。
  • 适用性​​:虚拟化环境(如容器)中可能无法提供完整的DMI信息。

代码部分

LinuxHardwareInfo.h

#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <string.h>
#include <sstream>
#include <memory>
#include <stdexcept>
#include <array>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <unordered_map>
#include <functional>

// CPU信息结构体
struct CPUInfo
{
    std::string processor_;              // CPU 的逻辑编号
    std::string vendor_id_;              // CPU 制造商的标识符
    std::string cpu_family_;             // CPU 所属的家族编号
    std::string model_;                  // CPU 型号编号
    std::string model_name_;             // CPU 的完整型号名称
    std::string stepping_;               // CPU 的步进编号
    std::string microcode_;              // CPU 微代码版本号
    std::string cpu_freq_;               // CPU 当前的运行频率,单位为 MHz
    std::string cache_size_;             // CPU 缓存的大小,单位为KB
    std::string physical_id_;            // CPU 的标识符
    std::string siblings_;               // 同一物理 CPU 上的逻辑处理器数量
    std::string core_id_;                // 每个物理核心的唯一标识符
    std::string cpu_cores_;              // 每个物理 CPU 中的核心数量,不包括超线程产生的逻辑核心
    std::string clflush_size_;           // 缓存行刷新(Cache Line Flush)操作所涉及的缓存行大小
};

// 磁盘信息结构体
struct DiskStatsInfo
{
    std::string major_device_num_;          // 主设备号,标识设备类型
    std::string minor_device_num_;          // 次设备号,用于在同一主设备类型下进一步区分具体的设备实例,主设备号和次设备号共同唯一标识系统中的一个块设备
    std::string device_name_;               // 磁盘名称,对应/dev目录下的设备文件名
    std::string read_completed_;            // 从设备成功完成的读操作次数,每次成功读取数据块,该计数增加
    std::string read_merged_;               // 合并读操作次数
    std::string read_sectors_;              // 从设备读取的扇区总数
    std::string read_time_spent_;           // 累计花费在读操作上的时间,单位毫秒
    std::string write_completed_;           // 向设备成功完成的写操作次数,每次成功写入数据块,该计数增加
    std::string write_merged_;              // 合并写操作次数
    std::string write_sectors_;             // 向设备写入的扇区总数
    std::string write_time_spent_;          // 累计花费在写操作上的时间,单位毫秒
};

// BIOS信息结构体,细节信息通过dmidecode命令获取到的
struct BIOSMoreInfo
{
    // 基础信息
    std::string     vendor_;                    // BIOS供应商
    std::string     version_;                   // BIOS版本
    std::string     date_;                      // BIOS发布日期
    
    // 细节信息
    std::string   address_;                     // BIOS 在内存中的物理地址(十六进制)
    std::string   runtime_size_;                // BIOS运行时占用的内存大小,单位为bytes
    std::string   rom_size_;                    // 存储 BIOS 固件的 ROM(只读存储器)容量,单位为kB
    std::string   bios_revision_;               // BIOS的修订版本号,可能与Version不同
    std::string   firmware_revisioin_;          // 主板固件版本号
};

// 主板信息结构体,细节信息通过dmidecode命令获取
struct BaseboardMoreInfo
{
    // 基础信息
    std::string     vendor_;                    // 主板供应商
    std::string     version_;                   // 主板版本号
    std::string     name_;                      // 主板型号
    std::string     asset_tag_;                 // 主板资产标签

    // 细节信息
    std::string     serial_num_;                // 主板序列号
    std::string     location_in_chassis_;       // 主板在机箱中的位置
    std::string     type_;                      // 主板类型
};

// 检测当前运行环境是否可以使用dmidecode命令
#ifndef IsUseDmidecodeCommand
#define IsUseDmidecodeCommand()\
    bool is_use_dmidecode = false;\
    \
    if(geteuid() == 0 && FindDmidecodePath())\
        is_use_dmidecode = true;\
    else\
        std::cout << "当前运行环境不支持dmidecode命令, 只获取基本信息" << std::endl;
#endif

// 根据:进行字符串切割并去除两端空格得到key和value字符串
#ifndef SplitRemoveWhite
#define SplitRemoveWhite(_line)\
    size_t pos = _line.find(':');\
    \
    if (pos == std::string::npos)\
        return;\
    \
    std::string key = _line.substr(0, pos);\
    std::string value = _line.substr(pos + 1);\
    \
    RemoveWhiteSpace(value);\
    RemoveWhiteSpace(key);
#endif

// Linux下获取CPU的所有信息
class LinuxHardwareInfo
{
public:

    LinuxHardwareInfo();
    ~LinuxHardwareInfo();

    /*
        @brief 获取CPU的所有信息
        @param _cpu_infos 会有多个cpu的信息
    */
    void GetProcessorAllInfo(std::vector<CPUInfo>& _cpu_infos);

    /*
        @brief 获取磁盘的所有信息
        @param _disk_infos 会有多个磁盘信息
    */
    void GetDiskStatsAllInfo(std::vector<DiskStatsInfo>& _disk_infos);

    /*
        @brief 获取BIOS的信息
            1、该接口会先使用demidecode命令获取BIOS更详细的信息,如果检测到系统的demidecode命令无法使用,改用读取文件的方式只获取BISO
                基本信息!!!
            2、该接口返回true的情况为:Linux系统已经安装demidecode命令,并且运行程序的用户为root用户
        @param _bios_info BIOS信息结构体
        @return true表示demidecode命令可以使用,获取到了更详细的信息;false说明当前运行环境的demidecode命令无法使用,只能获取基本信息。
    */
    bool GetBIOSAllInfo(BIOSMoreInfo& _bios_info);

    /*
        @brief 获取主板的信息
            1、该接口会先使用demidecode命令获取BIOS更详细的信息,如果检测到系统的demidecode命令无法使用,改用读取文件的方式只获取主板
                基本信息!!!
            2、该接口返回true的情况为:Linux系统已经安装demidecode命令,并且运行程序的用户为root用户
        @param _board_info 主板信息结构体
        @return true表示demidecode命令可以使用,获取到了更详细的信息;false说明当前运行环境的demidecode命令无法使用,只能获取基本信息。
    */
    bool GetBoardAllInfo(BaseboardMoreInfo& _board_info);

private:

    /*
        @brief 通过读取文件的方式获取BIOS基本信息
        @param BIOS基本信息
    */
    void GetBIOSBasicInfo(BIOSMoreInfo& _bios_info);

    /*
        @brief 通过读取文件的方式获取主板基本信息
        @param 主板基本信息
    */
    void GetBoardBasicInfo(BaseboardMoreInfo& _board_info);

    /*
        @brief 去除字符串两端的空白字符,包括空格、\t等
        @param _str 源字符串
    */
    void RemoveWhiteSpace(std::string& _str);

    /*
        @brief 解析CPU文件信息的一行
        @param _line 一行字符串
        @param _cpu_info 存储数据的结构体
    */
    void ParseProcessorLine(const std::string& _line, CPUInfo& _cpu_info);

    /*
        @brief 处理BISO信息的一行
        @param _line 一行字符串
        @param _bios_info BISO数据结构体
    */
    void ProcessBIOSLine(const std::string& _line, BIOSMoreInfo& _bios_info);

    /*
        @brief 处理主板信息的一行
        @param _line 一行字符串
        @param _board_info 主板数据结构体
    */
    void ProcessBoardLine(const std::string& _line, BaseboardMoreInfo& _board_info);

    /*
        @brief 检查 dmidecode 是否存在并返回其完整路径
        @return true表示存在,false表示不存在
    */
    bool FindDmidecodePath();

    /*
        @brief 执行命令并捕获输出
        @param cmd 命令
        @return 输出的字符串
    */
    std::string GetStrByCommand(const char* _cmd);

    /*
        @brief 按照换行符进行切割
        @param _str 源字符串
        @return 切割后的集合
    */
    std::vector<std::string> SplitByNewline(const std::string& _str);

    /*
        @brief 更新主板结构体处理器
        @param _key 结构体成员对应的key值
        @param value 结构体成员值
    */
    void UpdateBoardInfo(BaseboardMoreInfo& _board_info, const std::string& _key, const std::string& _value);

    /*
        @brief 更新BIOS结构体处理器
        @param _key 结构体成员对应的key值
        @param value 结构体成员值
    */
    void UpdateBIOSInfo(BIOSMoreInfo& _bios_info, const std::string& _key, const std::string& _value);

    /*
        @brief 更新CPU结构体处理器
        @param _key 结构体成员对应的key值
        @param value 结构体成员值
    */
    void UpdateCpuInfo(CPUInfo& _cpu_info, const std::string& _key, const std::string& _value);

private:

    // 成员指针类型别名
    using BoardMemberPtr = std::string BaseboardMoreInfo::*;

    using BIOSMemberPtr = std::string BIOSMoreInfo::*;

    using CpuMemberPtr = std::string CPUInfo::*;

    const std::string cpu_file_;        // Linux系统下cpu信息的存储路径

    const std::string disk_file_;       // Linux系统下磁盘信息的存储路径

    const std::string bios_dir_;                             // Linux系统下存放BIOS信息的目录
    const std::vector<std::string>  bios_files_name_;        // Linux系统下存放BIOS信息的所有文件名

    const std::string board_dir_;                             // Linux系统下存放主板信息的目录
    const std::vector<std::string>  board_files_name_;        // Linux系统下存放主板信息的所有文件名

    const std::vector<std::string>  dmidecode_command_path_; // Linux系统下常见的demidecode命令的完整路径,检测系统是否安装该命令会用到

    std::unordered_map<std::string, std::function<void(std::string)>>   process_board_value_map_;           // 给主板信息结构体赋值    
};

LinuxHardwareInfo.cpp

#include "LinuxHardwareInfo.h"

LinuxHardwareInfo::LinuxHardwareInfo()
    : cpu_file_("/proc/cpuinfo")
    , disk_file_("/proc/diskstats")
    , bios_dir_("/sys/class/dmi/id/")
    , bios_files_name_({"bios_vendor","bios_version","bios_date"})
    , dmidecode_command_path_({"/usr/sbin/dmidecode", "/sbin/dmidecode", "/usr/local/sbin/dmidecode"})
    , board_dir_("/sys/class/dmi/id/")
    , board_files_name_({"board_vendor","board_version","board_name","board_asset_tag"})
{
}

LinuxHardwareInfo::~LinuxHardwareInfo()
{
}

void LinuxHardwareInfo::GetProcessorAllInfo(std::vector<CPUInfo> &_cpu_info)
{
    std::ifstream file(cpu_file_);
    
    if (!file.is_open())
    {
        std::cerr << "CPU文件: " << cpu_file_ << "打开失败" << std::endl;

        return;
    }

    CPUInfo cpuInfo;
    std::string line;
    while (std::getline(file, line))
    {
        if (line.empty())
        {
            // 读取下一个cpu的信息
            if(!cpuInfo.model_name_.empty()) 
            {
                _cpu_info.push_back(cpuInfo);
                cpuInfo = CPUInfo();
            }
        }
        else
            ParseProcessorLine(line, cpuInfo);
    }

    // 添加最后一个CPU信息
    if (!cpuInfo.model_name_.empty()) 
    {
        _cpu_info.push_back(cpuInfo);
    }

    file.close();
}

void LinuxHardwareInfo::GetDiskStatsAllInfo(std::vector<DiskStatsInfo> &_disk_infos)
{
    std::ifstream disk_stats_file(disk_file_);
    if (!disk_stats_file.is_open()) 
    {
        std::cerr << "磁盘文件: " << disk_file_ << "打开失败" << std::endl;
     
        return;
    }

    std::string line;
    while (std::getline(disk_stats_file, line))
    {
        std::istringstream iss(line);

        DiskStatsInfo diskStats;

        std::string inFlight, ioTicks, timeInQueue;

        if (!(iss >> diskStats.major_device_num_ >> diskStats.minor_device_num_ >> diskStats.device_name_
                  >> diskStats.read_completed_ >> diskStats.read_merged_ >> diskStats.read_sectors_
                  >> diskStats.read_time_spent_ >> diskStats.write_completed_ 
                  >> diskStats.write_merged_ >> diskStats.write_sectors_ >> diskStats.write_time_spent_ 
                  >> inFlight >> ioTicks >> timeInQueue)) 
        {
            continue;
        }

        _disk_infos.push_back(diskStats);
    }

    disk_stats_file.close();

    return;
}

bool LinuxHardwareInfo::GetBIOSAllInfo(BIOSMoreInfo &_bios_info)
{
    IsUseDmidecodeCommand()

    if(is_use_dmidecode)   // 使用dmidecode命令获取更详细的BISO信息
   python {
        try
        {
            // 对获取到的命令输出进行字符串切割
            std::vector<std::string> bios_info_vec = SplitByNewline(GetStrByCommand("dmidecode -t bios"));

            for(const auto& line : bios_info_vec)
            {
                ProcessBIOSLine(line, _bios_info);
            }

        } catch (const std::exception& e)
        {
            std::cerr << "dmidecode命令执行错误: " << e.what() << std::endl;

            // 抛出异常后只获取基本信息
            GetBIOSBasicInfo(_bios_info);

            return false;
        }
    }
    else    // 只获取基本信息
        GetBIOSBasicInfo(_bios_info);

    return is_use_dmidecode;
}

bool LinuxHardwareInfo::GetBoardAllInfo(BaseboardMoreInfo &_board_info)
{
    IsUseDmidecodeCommand()

    if(is_use_dmidecode)   // 使用dmidecode命令获取更详细的主板信息
    {
        try
        {
            // 对获取到的命令输出进行字符串切割
            std::vector<std::string> board_info_vec = SplitByNewline(GetStrByCommand("dmidecode -t baseboard"));

            bool is_parse = false;
            for(const auto& line : board_info_vec)
            {
                if(line == "Base Board Information")
                    is_parse = true;
                else if(line.empty())
                    is_parse = false;
                
                if(is_parse)
                    ProcessBoardLine(line, _board_info);
            }

        } catch (const std::exception& e)
        {
            std::cerr << "dmidecode命令执行错误: " << e.what() << std::endl;

            // 抛出异常后只获取基本信息
            GetBoardBasicInfo(_board_info);

            return false;
        }
    }
    else    // 只获取基本信息
        GetBoardBasicInfo(_board_info);

    return is_use_dmidecode;
}

void LinuxHardwareInfo::GetBIOSBasicInfo(BIOSMoreInfo &_bios_info)
{
    for(const auto& file_name : bios_files_name_)
    {
        // bios文件路径
        std::string path = bios_dir_ + file_name;
        std::ifstream file(path);
        if (!file.is_open())
        {
            std::cerr << "BIOS文件: " << path << "打开失败" << std::endl;
            return;
        }

        std::string value;
        std::getline(file, value);
        
        UpdateBIOSInfo(_bios_info,file_name,value);
    }
}

void LinuxHardwareInfo::GetBoardBasicInfo(BaseboardMoreInfo &_board_info)
{
    for(const auto& file_name : board_files_name_)
    {
        // board文件路径
        std::string path = board_dir_ + file_name;
        std::ifstream file(path);
        if (!file.is_open())
        {
            std::cerr << "主板文件: " << path << "打开失败" << std::endl;
            return;
        }

        std::string value;
        std::getline(file, value);
        
        UpdateBoardInfo(_board_info,file_name,value);
    }
}

void LinuxHardwareInfo::RemoveWhiteSpace(std::string &_str)
{
    int head_idx = 0, tail_idx = _str.length() - 1;

    bool head_flag = false, tail_flag = false;

    while (head_idx != tail_idx)
    {
        // 使用std::isspace方法判断空白字符,因为会有\t等情况
        if(!head_flag && std::isspace(_str[head_idx]))
            head_idx++;
        else
            head_flag = true;

        if(!tail_flag && std::isspace(_str[tail_idx]))
            tail_idx--;
        else
            tail_flag = true;

        if(head_flag && tail_flag)
            break;
    }

    _str = _str.substr(head_idx, tail_idx - head_idx + 1);

    return;
}

void LinuxHardwareInfo::ParseProcessorLine(const std::string &_line, CPUInfo &_cpu_info)
{
    SplitRemoveWhite(_line)

    UpdateCpuInfo(_cpu_info,key,value);
}

void LinuxHardwareInfo::ProcessBIOSLine(const std::string &_line, BIOSMoreInfo &_bios_info)
{
    SplitRemoveWhite(_line)

    UpdateBIOSInfo(_bios_info,key,value);
}

void LinuxHardwareInfo::ProcessBoardLine(const std::string &_line, BaseboardMoreInfo &_board_info)
{
    SplitRemoveWhite(_line)

    UpdateBoardInfo(_board_info,key,value);
}

bool LinuxHardwareInfo::FindDmidecodePath()
{
    for (const auto& path : dmidecode_command_path_) 
    {
        if (Access(path.c_str(), X_OK) == 0) 
        {
            return true; // 找到有效路径
        }
    }

    return false;
}

std::string LinuxHardwareInfo::GetStrByCommand(const char *_cmd)
{
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(_cmd, "r"), pclose);

    if (!pipe) 
    {
        throw std::runtime_error("Failed to execute command");
    }

    while (fgets(buffer.daandroidta(), buffer.size(), pipe.get()) != nullptr) 
    {
        result += buffer.data();
    }

    return result;
}

std::vector<std::string> LinuxHardwareInfo::SplitByNewline(const std::string &_str)
{
    std::vector<std::string> lines;
    std::istringstream iss(_str);
    std::string line;   
    
    while (std::getline(iss, line, '\n')) 
    {
        lines.push_back(line);
    }

    return lines;
}

void LinuxHardwareInfo::UpdateBoardInfo(BaseboardMoreInfo &_board_info, const std::string &_key, const std::string &_value)
{
    static const std::unordered_map<std::string, BoardMemberPtr> keys_map = {
        {"Manufacturer",   &BaseboardMoreInfo::vendor_},
        {"Product Name",   &BaseboardMoreInfo::name_},
        {"Version",  &BaseboardMoreInfo::version_},
        {"Serial Number",       &BaseboardMoreInfo::serial_num_},
        {"Asset Tag",  &BaseboardMoreInfo::asset_tag_},
        {"Location In Chassis",    &BaseboardMoreInfo::location_in_chassis_},
        {"Type",    &BaseboardMoreInfo::type_},
        {"board_vendor",   &BaseboardMoreInfo::vendor_},
        {"board_name",   &BaseboardMoreInfo::name_},
        {"board_version",   &BaseboardMoreInfo::version_},
        {"board_asset_tag",   &BaseboardMoreInfo::asset_tag_},
        {"board_serial",   &BaseboardMoreInfo::serial_num_}
    };

    if (auto it = keys_map.find(_key); it != keys_map.end()) 
    {
        _board_info.*(it->second) = _value;
    }
    // else
    //     std::cerr << "解析出" << _key << "和" << _value << std::endl;
}

void LinuxHardwareInfo::UpdateBIOSInfo(BIOSMoreInfo &_bios_info, const std::string &_key, const std::string &_value)
{
    static const std::unordered_map<std::string, BIOSMemberPtr> keys_map = {
        {"Vendor",   &BIOSMoreInfo::vendor_},
        {"Release Date",   &BIOSMoreInfo::date_},
        {"Version",  &BIOSMoreInfo::version_},
        {"Address",       &BIOSMoreInfo::address_},
        {"Runtime Size",  &BIOSMoreInfo::runtime_size_},
        {"ROM Size",    &BIOSMoreInfo::rom_size_},
        {"BIOS Revision",    &BIOSMoreInfo::bios_revision_},
        {"Firmware Revision",    &BIOSMoreInfo::firmware_revisioin_},
        {"bios_vendor",   &BIOSMoreInfo::vendor_},
        {"bios_date",   &BIOSMoreInfo::date_},
        {"bios_version",   &BIOSMoreInfo::version_}
    };

    if (auto it = keys_map.find(_key); it != keys_map.end()) 
    {
        // 部分字段带有单位,去除单位
        if(_value.find(" ") != std::string::npos)
        {
            size_t pos = _value.find(" ");

            _bios_info.*(it->second) = _value.substr(0, pos);
        }
        else
            _bios_info.*(it->second) = _value;
    }
    // else
    //     std::cerr << "解析出" << _key << "和" << _value << std::endl;
}

void LinuxHardwareInfo::UpdateCpuInfo(CPUInfo& _cpu_info, const std::string &_key, const std::string &_value)
{
    static const std::unordered_map<std::string, CpuMemberPtr> keys_map = {
        {"processor",   &CPUInfo::processor_},
        {"vendor_id",   &CPUInfo::vendor_id_},
        {"cpu family",  &CPUInfo::cpu_family_},
        {"model",       &CPUInfo::model_},
        {"model name",  &CPUInfo::model_name_},
        {"stepping",    &CPUInfo::stepping_},
        {"microcode",    &CPUInfo::microcode_},
        {"cpu MHz",    &CPUInfo::cpu_freq_},
        {"physical id",   &CPUInfo::physical_id_},
        {"siblings",   &CPUInfo::siblings_},
        {"core id",   &CPUInfo::core_id_},
        {"cpu cores",   &CPUInfo::cpu_cores_},
        {"clflush size",   &CPUInfo::clflush_size_}
    };

    if (auto it = keys_map.find(_key); it != keys_map.end()) 
    {
        // 部分字段带有单位,去除单位
        if(_value.find(" ") != std::string::npos)
        {
            size_t pos = _value.find(" ");

            _cpu_info.*(it->second) = _value.substr(0, pos);
        }
        else
            _cpu_info.*(it->second) = _value;
    }
    // else
    //     std::cerr << "解析出" << _key << "和" << _value << std::endl;
}

main.cpp

#include <iostream>
#include "LinuxHardwareInfo.h"
int main()
{
    LinuxHardwareInfo info;

    std::cout << "*************************CPU信息*************************" << std::endl;

    std::vector<CPUInfo> cpuInfos;
    info.GetProcessorAllInfo(cpuInfos);

    for (const auto& cpuInfo : cpuInfos)
    {
        std::cout << "-------------------------" << std::endl;
        std::cout <js;< "processor: " << cpuInfo.processor_ << std::endl;
        std::cout << "Vendor ID: " << cpuInfo.vendor_id_ << std::endl;
        std::cout << "CPU Family: " << cpuInfo.cpu_family_ << std::endl;
        std::cout << "Model: " << cpuInfo.model_ << std::endl;
        std::cout << "Model Name: " << cpuInfo.model_name_ << std::endl;
        std::cout << "Stepping: " << cpuInfo.stepping_ << std::endl;
        std::cout << "Microcode: " << cpuInfo.microcode_ << std::endl;
        std::cout << "CPU MHz: " << cpuInfo.cpu_freq_ << std::endl;
        std::cout << "Cache Size: " << cpuInfo.cache_size_ << std::endl;
        std::cout << "Physical ID: " << cpuInfo.physical_id_ << std::endl;
        std::cout << "Siblings: " << cpuInfo.siblings_ << std::endl;
        std::cout << "Core ID: " << cpuInfo.core_id_ << std::endl;
        std::cout << "CPU Cores: " << cpuInfo.cpu_cores_ << std::endl;
        std::cout << "clflush size: " << cpuInfo.clflush_size_ << std::endl;
        std::cout << "-------------------------" << std::endl;
    }

    std::cout << "*************************CPU信息*************************" << std::endl;

    std::cout << "*************************磁盘信息*************************" << std::endl;

    std::vector<DiskStatsInfo> disk_infos;
    info.GetDiskStatsAllInfo(disk_infos);

    for (const auto& diskStats : disk_infos) 
    {
        std::cojavascriptut << "-------------------------" << std::endl;
        std::cout << "主设备号: " << diskStats.major_device_num_ << std::endl;
        std::cout << "次设备号: " << diskStats.minor_device_num_ << std::endl;
        std::cout << "磁盘名称: " << diskStats.device_name_ << std::endl;
        std::cout << "完成的读操作次数: " << diskStats.read_completed_ << std::endl;
        std::cout << "合并读操作次数: " << diskStats.read_merged_ << std::endl;
        std::cout << "读取的扇区总数: " << diskStats.read_sectors_ << std::endl;
        std::cout << "花费在读操作上的时间: " << diskStats.read_time_spent_ << std::endl;
        std::cout << "完成的写操作次数: " << diskStats.write_completed_ << std::endl;
        std::cout << "合并写操作次数: " << diskStats.write_merged_ << std::endl;
        std::cout << "写入的扇区总数: " << diskStats.write_sectors_ << std::endl;
        std::cout << "花费在写操作上的时间: " << diskStats.write_time_spent_ << std::endl;
        std::cout << "-------------------------" << std::endl;
    }
    std::cout << "*************************磁盘信息*************************" << std::endl;

    std::cout << "*************************BIOS信息*************************" << std::endl;

    BIOSMoreInfo bios_info;
    info.GetBIOSAllInfo(bios_info);

    std::cout << "BIOS版本号: " << bios_info.version_ << std::endl;
    std::cout << "BIOS供应商: " << bios_info.vendor_ << std::endl;
    std::cout << "BIOS发布日期: " << bios_info.date_ << std::endl;
    std::cout << "BIOS 在内存中的物理地址: " << bios_info.address_ << std::endl;
    std::cout << "BIOS运行时占用的内存大小: " << bios_info.runtime_size_ << std::endl;
    std::cout << "存储BIOS固件的ROM(只读存储器)容量: " << bios_info.rom_size_ << std::endl;
    std::cout << "BIOS 的修订版本号: " << bios_info.bios_revision_ << std::endl;
    std::cout << "主板固件的版本号: " << bios_info.firmware_revisioin_ << std::endl;
    std::cout << "*************************BIOS信息*************************" << std::endl;
 
    std::cout << "*************************主板信息*************************" << std::endl;
 
    BaseboardMoreInfo board_info;
    info.GetBoardAllInfo(board_info);
 
    std::cout << "主板版本号: " << board_info.version_ << std::endl;
    std::cout << "主板供应商: " << board_info.vendor_ << std::endl;
    std::cout << "主板型号: " << board_info.name_ << std::endl;
    std::cout << "主板序列号: " << board_info.serial_num_ << std::endl;
    std::cout << "主板资产标签: " << board_info.asset_tag_ << std::endl;
    std::cout << "主板在机箱中的位置: " << board_info.location_in_chassis_ << std::endl;
    std::cout << "主板类型: " << board_info.type_ << std::endl;
    std::cout << "*************************主板信息*************************" << std::endl;

    return 0;
}

代码链接

代码地http://www.devze.com

部分运行结果

Linux下如何使用C++获取硬件信息

Linux下如何使用C++获取硬件信息

以上就是Linux下如何使用C++获取硬件信息的详细内容,更多关于C++获取硬件信息的资料请关注编程客栈(www.devze.com)其它相关文章!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜