content
1 X86 linux get cpu ID
In x86 Linux, we can use the following command on the command line to get the cpu ID
dmidecode -t 4 | grep ID
If you want to implement it in code, use the following code
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 get cpu ID
In ARM Linux we use the following command on the command line to get the cpu ID,
cat /proc/cpuinfo | grep Serial
If you want to implement it with code, you can use the following code
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 获tori cpu name
Whether it is X86 linux or ARM Linux, we can use the following command on the command line to get the cpu name,
cat /proc/cpuinfo | grep model
If you want to implement it in code, you can use the following code
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;
}