在Linux中从/proc文件系统获取硬件信息

问题描述:

我使用execv运行lshw命令以C代码获取CPU,磁盘和内存.但我想搜索另一种解决方案,以从/proc或任何其他现有数据中获取这些信息.有什么建议吗?这是我的代码:

I use execv to run lshw command to get the CPU, disk, and memory in C code. But I would like to search another solution to get these information from /proc or any other existed data. Have any suggestion? Here is my code:

char *params[9]  = {"/usr/bin/lshw", "-short", "-c", "disk", 
                  "-c", "memory", "-c", "processor", 0}; //cmd params filled
execv(params[0], params);

Linux命令:$ sudo lshw -short -c disk -c processor -c memory

$ sudo lshw -short -c disk -c processor -c memory
H/W path         Device     Class          Description
======================================================
/0/0                        memory         64KiB BIOS
/0/22                       memory         16GiB System Memory
/0/22/0                     memory         DIMM Synchronous [empty]
/0/22/1                     memory         DIMM Synchronous [empty]
/0/22/2                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/22/3                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/2a                       memory         256KiB L1 cache
/0/2b                       memory         1MiB L2 cache
/0/2c                       memory         6MiB L3 cache
/0/2d                       processor      Intel(R) Xeon(R) CPU D-1521 @ 2.40GHz
/0/1/0.0.0       /dev/sda   disk           16GB SATADOM-SH 3IE3
/0/2/0.0.0       /dev/sdb   disk           120GB Patriot Blaze

我有两个问题:

  • 在哪里可以找到解析/proc中文件的指南,以获取 这些硬件信息?
  • 我是否需要跟踪lshw的源代码以查找lshw的作用?
  • Where to find a guide to parse the files in /proc to get these hardware information?
  • Do I need to trace the source code of lshw to find what does lshw do?

高级Linux编程的第7章是解析/proc文件系统的指南.

Chapter 7 of Advanced Linux Programming is a guide to parse the /proc filesystem.

通过阅读lshw的源代码,我发现lshw/sys/class/dmi/读取原始数据.由于lshw是用我不熟悉的CPP编写的,因此存在一个问题 dmidecode在哪里获取SMBIOS表?提到dmidecode.c/sys/class/dmi读取原始数据,与lshw相同.

By reading the source code of lshw, I found that lshw read raw data from /sys/class/dmi/. Because lshw is written in CPP that I am not familiar with, there is a question Where does dmidecode get the SMBIOS table? mentioned that dmidecode.c read raw data from /sys/class/dmi that's same as lshw does.

这是dmidecode.c

#define SYS_ENTRY_FILE "/sys/firmware/dmi/tables/smbios_entry_point"
#define SYS_TABLE_FILE "/sys/firmware/dmi/tables/DMI"

我从dmidecode.c 以获取CPU和内存信息,并使用 lsscsi 来获取磁盘信息.

I extract code from dmidecode.c to get the CPU and memory information, and use lsscsi to get disk information.

感谢您的帮助.