2017-01-16 213 views
3

我想知道如何在GNU Linux上可靠地獲取處理器序列號(PSN)。C/C++如何在linux上獲取處理器序列號

現在我使用這個

#include <stdio.h> 
#include <cpuid.h> 

unsigned int level = 1; 
unsigned eax = 3 /* processor serial number */, ebx = 0, ecx = 0, edx = 0; 
__get_cpuid(level, &eax, &ebx, &ecx, &edx); 

// byte swap 
int first = ((eax >> 24) & 0xff) | ((eax << 8) & 0xff0000) | ((eax >> 8) & 0xff00) | ((eax << 24) & 0xff000000); 
int last = ((edx >> 24) & 0xff) | ((edx << 8) & 0xff0000) | ((edx >> 8) & 0xff00) | ((edx << 24) & 0xff000000); 

printf("PSN: %08X%08X", first, last); 

它給我PSN: A7060200FFFBEBBF

sudo dmidecode | grep -P '^\s+ID: ([0-9A-F]{2}){7}[0-9A-F]{2}$' 

輸出相匹配:ID: A7 06 02 00 FF FB EB BF

我只在英特爾酷睿測試我處理器,所以也許它只適用於這種類型的CPU。

我知道「序列號」在相同的CPU型號上是相同的,因此不是唯一的。

此外,我期待着實現這一目標的方法,即不依賴執行shell命令和解析輸出。

+0

希望[這](http://stackoverflow.com/questions/6491566/getting-the-machine-serial-number-and-cpu- id-using-cc-in-linux)有幫助。 – GAVD

+0

謝謝,我的代碼片段已經從這個答案中得到了啓發,但不幸的是它適用於Intel Pentum III。他還使用asm只用於x86的易失性代碼,這是我所避免的。他也沒有使用相同的值,使用的水平是0,這對我沒有用,他使用了不同的寄存器,ecx edx,而我的eax edx。 – Annihil

+0

它將適用於AMD,但不適用於所有ARM處理器 –

回答

0

可以使用POPEN,然後分析結果

unsigned char *pk = new unsigned char[100]; 
    FILE *source = popen("lscpu", "r"); 
    while (!feof(source)) { 
     fread(pk, 100, 1, source); 
     for(int i=0;i<100;++i) 
     { 
      printf("%c",pk[i]); 
     } 
     printf("\n"); 
    } 
    pclose(source); 
+0

謝謝,但我正在尋求一種不依賴於執行shell命令並檢索輸出的解決方案。 – Annihil