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

29

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

非常感谢提供示例代码。


9
@viraptor,第一页上没有真正的答案。现在这个问题是第一个搜索结果,如果它能得到一个真正的答案就太好了。这也是 Stack Overflow 的目的之一,为特定的问题提供规范化的回答,而不需要像论坛那样有很多无用的内容。 - nos
1
“机器序列号”是指CPU的序列号还是主板序列号? - Andre Holzner
1
@viraptor 确实非常有趣。有许多答案被点赞,甚至有一个被接受了,即使它根本没有回答问题。我想我会给所有答案投反对票并举报这个问题。说真的,这太荒谬了。即使Andre Holzner要求澄清,然后只是发表了一些东西来参加得分比赛,然后因为一个垃圾答案而被接受了。 - Kenyakorn Ketsombut
5个回答

32

这里是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指令的好参考资料在这篇维基百科文章中

编辑 维基百科文章中提到,序列号是在Pentium III中引入的,但由于隐私问题在后来的型号中不再实现。在Linux系统上,您可以通过执行以下操作检查此功能的存在(PSN位):

grep -i --color psn /proc/cpuinfo

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


此调用的结果不是“序列号”。它是计算机安装的CPU型号的非唯一标识符(例如,“Intel Xeon E5-2630”)。 - user149341
事实上,在英特尔CPU中,只有Pentium III似乎支持它(仅在BIOS中启用时)。我更新了答案。 - Andre Holzner

23

在GCC中有一个名为cpuinfo.h的头文件,它是安全的,请使用它。

示例(我使用GCC 4.7+并在这里使用“auto”感到很高兴):

#include <cpuid.h>
#include <iostream>
#include <map>
#include <string>

using namespace std;

struct CPUVendorID {
    unsigned int ebx;
    unsigned int edx;
    unsigned int ecx;

    string toString() const {
        return string(reinterpret_cast<const char *>(this), 12);
    }
};

int main() {
    unsigned int level = 0;
    unsigned int eax = 0;
    unsigned int ebx;
    unsigned int ecx;
    unsigned int edx;

    __get_cpuid(level, &eax, &ebx, &ecx, &edx);

    CPUVendorID vendorID { .ebx = ebx, .edx = edx, .ecx = ecx };

    map<string, string> vendorIdToName;
    vendorIdToName["GenuineIntel"] = "Intel";
    vendorIdToName["AuthenticAMD"] = "AMD";
    vendorIdToName["CyrixInstead"] = "Cyrix";
    vendorIdToName["CentaurHauls"] = "Centaur";
    vendorIdToName["SiS SiS SiS "] = "SiS";
    vendorIdToName["NexGenDriven"] = "NexGen";
    vendorIdToName["GenuineTMx86"] = "Transmeta";
    vendorIdToName["RiseRiseRise"] = "Rise";
    vendorIdToName["UMC UMC UMC "] = "UMC";
    vendorIdToName["Geode by NSC"] = "National Semiconductor";

    string vendorIDString = vendorID.toString();

    auto it = vendorIdToName.find(vendorIDString);
    string vendorName = (it == vendorIdToName.end()) ? "Unknown" : it->second;

    cout << "Max instruction ID: " << eax << endl;
    cout << "Vendor ID: " << vendorIDString << endl;
    cout << "Vendor name: " << vendorName << endl;
}

输出:

$ make
g++ --std=c++11 main.cc -o cpuid
$ ./cpuid 
Max instruction ID: 6
Vendor ID: GenuineIntel
Vendor name: Intel

8
您可以从/proc/cpuinfo中提取有关处理器的信息。 要获取序列号,您应该查看dmidecode。我现在没有查看那里,但是dmidecode能够显示序列号,因此我会从那里开始。

3
#include <stdio.h>

void getPSN(char *PSN)
{
    int varEAX, varEBX, varECX, varEDX;
    char str[9];
    //%eax=1 gives most significant 32 bits in eax 
    __asm__ __volatile__ ("cpuid"   : "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (1));
    sprintf(str, "%08X", varEAX); //i.e. XXXX-XXXX-xxxx-xxxx-xxxx-xxxx
    sprintf(PSN, "%C%C%C%C-%C%C%C%C", str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
    //%eax=3 gives least significant 64 bits in edx and ecx [if PN is enabled]
    __asm__ __volatile__ ("cpuid"   : "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (3));
    sprintf(str, "%08X", varEDX); //i.e. xxxx-xxxx-XXXX-XXXX-xxxx-xxxx
    sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
    sprintf(str, "%08X", varECX); //i.e. xxxx-xxxx-xxxx-xxxx-XXXX-XXXX
    sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
}

int main()
{
     char PSN[30]; //24 Hex digits, 5 '-' separators, and a '\0'
     getPSN(PSN);
    printf("%s\n", PSN); //compare with: lshw | grep serial:
     return 0;
}

1

这个程序将帮助您通过程序运行Linux命令:

char* GetSystemOutput(char* cmd)
{
    int buff_size = 32;
    char* buff = new char[buff_size];

    char* ret = NULL;
    string str = "";

    int fd[2];
    int old_fd[3];
    pipe(fd);

    old_fd[0] = dup(STDIN_FILENO);
    old_fd[1] = dup(STDOUT_FILENO);
    old_fd[2] = dup(STDERR_FILENO);

    int pid = fork();
    switch(pid)
    {
        case 0:
               close(fd[0]);
               close(STDOUT_FILENO);
               close(STDERR_FILENO);
               dup2(fd[1], STDOUT_FILENO);
               dup2(fd[1], STDERR_FILENO);
               system(cmd);
               //execlp((const char*)cmd, cmd,0);
               close (fd[1]);
               exit(0);
               break;

        case -1:
               cerr << "GetSystemOutput/fork() error\n" << endl;
               exit(1);

        default:
               close(fd[1]);
               dup2(fd[0], STDIN_FILENO);

               int rc = 1;
               while (rc > 0)
               {
                   rc = read(fd[0], buff, buff_size);
                   str.append(buff, rc);
                   //memset(buff, 0, buff_size);
               }

               ret = new char [strlen((char*)str.c_str())];

               strcpy(ret, (char*)str.c_str());

               waitpid(pid, NULL, 0);
               close(fd[0]);
    }

    dup2(STDIN_FILENO, old_fd[0]);
    dup2(STDOUT_FILENO, old_fd[1]);
    dup2(STDERR_FILENO, old_fd[2]);

    return ret;
}

API使用:GetSystemOutput(“/usr/bin/lsb_release -a”)

接下来执行以下命令:

cat /proc/cpuinfo = tells you CPU information

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接