目录
1 X86 linux获取cpu ID
2 ARM linux获取cpu ID
?3 获取cpu name
1 X86 linux获取cpu ID
我们在x86 Linux中可以在命令行中用如下命令来得到cpu ID
dmidecode -t 4 | grep ID
如果想在代码中实现,用如下代码
static inline char* skip_ws(const char *p)
{
while (isspace(*p)) p++;
return (char *)p;
}
static inline char* skip_token(const char *p)
{
while (isspace(*p)) p++;
while (*p && !isspace(*p)) p++;
return (char *)p;
}
int GetCpuIdByAsm(char* cpu_id)
{
char cpuId[40]={0};
size_t length = 0;
FILE * fp = popen("dmidecode -t 4 | grep ID", "r");
if (fp)
{
char* ci = fgets(cpuId, sizeof(cpuId) - 1, fp);
if (ci)
{
char* pstr = skip_ws(skip_token(cpuId));
char* pchar = pstr;
while(*pchar)
{
if(*pchar == ' ' )
{ // is space
*pchar++ = '-';
}
else
{
++pchar;
}
}
memcpy(cpu_id, pstr, strlen(cpuId));
}
else
{
return -1;
}
pclose(fp);
}
return 0;
}
2 ARM linux获取cpu ID
在ARM Linux中我们在命令行中使用如下命令得到cpu ID,
cat /proc/cpuinfo | grep Serial
如果想用代码实现,可以用如下代码?
int GetCpuIdByAsm(char* cpu_id)
{
FILE *fp = fopen("/proc/cpuinfo", "r");
if(NULL == fp)
printf("failed to open cpuinfo\n");
char cpuSerial[100] = {0};
while(!feof(fp))
{
memset(cpuSerial, 0, sizeof(cpuSerial));
fgets(cpuSerial, sizeof(cpuSerial) - 1, fp); // leave out \n
char* pch = strstr(cpuSerial,"Serial");
if (pch)
{
char* pch2 = strchr(cpuSerial, ':');
if (pch2)
{
memmove(cpu_id, pch2 + 2, strlen(cpuSerial));
break;
}
else
{
return -1;
}
}
}
fclose(fp);
return 0;
}
?3 获取cpu name
无论是X86 linux还是ARM Linux,我们都可以在命令行中使用如下命令得到cpu name,
cat /proc/cpuinfo | grep model
如果想在代码中实现可以使用如下代码?
int GetCpuInfo(char* cpuName)
{
FILE *fp = fopen("/proc/cpuinfo", "r");
if(NULL == fp)
printf("failed to open cpuinfo\n");
char cpuModel[100] = {0};
while(!feof(fp))
{
memset(cpuModel, 0, sizeof(cpuModel));
fgets(cpuModel, sizeof(cpuModel) - 1, fp); // leave out \n
char* pch = strstr(cpuModel,"model name");
if (pch)
{
char* pch2 = strchr(cpuModel, ':');
if (pch2)
{
memmove(cpuName, pch2 + 2, strlen(cpuModel));
break;
}
else
{
return -1;
}
}
}
fclose(fp);
return 0;
}
|