C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++获取硬件信息

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

作者:ACE叫牌

这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

方法

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

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

字段及其含义:

处理器基本信息:

处理器型号与家族信息

步进与微代码信息:

性能相关信息:

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

多处理器与多核信息:

其他信息:

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

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

获取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

字段含义:

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

缺点:​

获取主板信息有两种方法

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

字段含义:

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

缺点:​

代码部分

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信息
    {
        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.data(), 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 << "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::cout << "-------------------------" << 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;
}

代码链接

代码地址

部分运行结果

以上就是Linux下如何使用C++获取硬件信息的详细内容,更多关于C++获取硬件信息的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文