c++ - 在 Linux 中使用 C/C++ 获取机器序列号和 CPU ID

标签 c++ c linux

如何在Linux系统中获取机器序列号和CPU ID?

非常感谢示例代码。

最佳答案

Here是Linux内核似乎使用的:

static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,
                                unsigned int *ecx, unsigned int *edx)
{
        /* ecx is often an input as well as an output. */
        asm volatile("cpuid"
            : "=a" (*eax),
              "=b" (*ebx),
              "=c" (*ecx),
              "=d" (*edx)
            : "0" (*eax), "2" (*ecx));
}

然后哪个可以用作例如:

#include <stdio.h>

int main(int argc, char **argv)
{
  unsigned eax, ebx, ecx, edx;

  eax = 1; /* processor info and feature bits */
  native_cpuid(&eax, &ebx, &ecx, &edx);

  printf("stepping %d\n", eax & 0xF);
  printf("model %d\n", (eax >> 4) & 0xF);
  printf("family %d\n", (eax >> 8) & 0xF);
  printf("processor type %d\n", (eax >> 12) & 0x3);
  printf("extended model %d\n", (eax >> 16) & 0xF);
  printf("extended family %d\n", (eax >> 20) & 0xFF);

  /* EDIT */
  eax = 3; /* processor serial number */
  native_cpuid(&eax, &ebx, &ecx, &edx);

  /** see the CPUID Wikipedia article on which models return the serial 
      number in which registers. The example here is for 
      Pentium III */
  printf("serial number 0x%08x%08x\n", edx, ecx);

}

关于如何使用CPUID 指令的一个很好的引用在this Wikipedia article 中。 .

编辑 Wikipedia 文章称,序列号是在 Pentium III 中引入的,但由于隐私问题不再在以后的模型中实现。在 Linux 系统上,您可以通过以下方式检查此功能(PSN 位)是否存在:

grep -i --color psn /proc/cpuinfo

如果这没有显示任何内容,则您的系统不支持处理器序列号。

关于c++ - 在 Linux 中使用 C/C++ 获取机器序列号和 CPU ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491566/

相关文章:

c++ - 如何在 C++ 中使用嵌套模板?

c++ - VxWorks spyLib 的可变函数指针定义不清楚

c - 文件读取错误值

linux - 从 _start 调用 printf 时出现链接器错误

linux - 无法安装快照

c++ - 当我尝试使用按钮添加 QTabWidget 时 Appcrash

c++ - 难以理解虚函数

c - 如何将二进制数据添加(和使用)到已编译的可执行文件中?

c - P线程同步: Back & Forth Reading of Two Text Files

linux - 删除每 4 行末尾的逗号