获取 CPU 序列号

受lshw的启发,自己动手写了一个获取Intel CPU序列号的小程序,顺便练练gcc内嵌汇编。过程中参考了Intel手册和lshw源代码。:-)

注意:并不是所有的Intel CPU都有序列号。我的CPU就不行,又在别的机器上测的。

[c]

include

typedef struct {
unsigned int eax;
unsigned int edx;
unsigned int ecx;
} cpusn_t;

int getcpusn(cpusnt *sn)
{
sn->eax = 1;
asm (
“cpuidnt”
:”=c”(sn->ecx), “=d”(sn->edx), “=a” (sn->eax)
:”2” (sn->eax)
);
if ((sn->edx & (1<eax = 3;
__asm
(
“cpuidnt”
:”=c”(sn->ecx), “=d”(sn->edx), “=a” (sn->eax)
:”2” (sn->eax)
);
return 0;
}
void print_cpusn(cpusn_t sn)
{
char buf[30];
snprintf(buf, sizeof(buf), “%04X-%04X-%04X-%04X-%04X-%04X”,
sn.eax >> 16, sn.eax & 0xffff,
sn.edx >> 16, sn.edx & 0xffff,
sn.ecx >> 16, sn.ecx & 0xffff);
printf(“%sn”, buf);

}

int main(void)
{
cpusn_t sn = {0, 0, 0};
if (get_cpusn(&sn) == 0) {
print_cpusn(sn);
} else {
//printf(“edx = %xn”, sn.edx);
printf(“Doesn’t support this.n”);
}
return 0;
}
[/c]