当前位置:   article > 正文

C/C++获取cpu的id和名字_c获取设备id

c获取设备id

目录

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

如果想在代码中实现,用如下代码

  1. static inline char* skip_ws(const char *p)
  2. {
  3. while (isspace(*p)) p++;
  4. return (char *)p;
  5. }
  6. static inline char* skip_token(const char *p)
  7. {
  8. while (isspace(*p)) p++;
  9. while (*p && !isspace(*p)) p++;
  10. return (char *)p;
  11. }
  12. int GetCpuIdByAsm(char* cpu_id)
  13. {
  14. char cpuId[40]={0};
  15. size_t length = 0;
  16. FILE * fp = popen("dmidecode -t 4 | grep ID", "r");
  17. if (fp)
  18. {
  19. char* ci = fgets(cpuId, sizeof(cpuId) - 1, fp);
  20. if (ci)
  21. {
  22. char* pstr = skip_ws(skip_token(cpuId));
  23. char* pchar = pstr;
  24. while(*pchar)
  25. {
  26. if(*pchar == ' ' )
  27. { // is space
  28. *pchar++ = '-';
  29. }
  30. else
  31. {
  32. ++pchar;
  33. }
  34. }
  35. memcpy(cpu_id, pstr, strlen(cpuId));
  36. }
  37. else
  38. {
  39. return -1;
  40. }
  41. pclose(fp);
  42. }
  43. return 0;
  44. }

2 ARM linux获取cpu ID

在ARM Linux中我们在命令行中使用如下命令得到cpu ID,

cat /proc/cpuinfo | grep Serial

如果想用代码实现,可以用如下代码 

  1. int GetCpuIdByAsm(char* cpu_id)
  2. {
  3. FILE *fp = fopen("/proc/cpuinfo", "r");
  4. if(NULL == fp)
  5. printf("failed to open cpuinfo\n");
  6. char cpuSerial[100] = {0};
  7. while(!feof(fp))
  8. {
  9. memset(cpuSerial, 0, sizeof(cpuSerial));
  10. fgets(cpuSerial, sizeof(cpuSerial) - 1, fp); // leave out \n
  11. char* pch = strstr(cpuSerial,"Serial");
  12. if (pch)
  13. {
  14. char* pch2 = strchr(cpuSerial, ':');
  15. if (pch2)
  16. {
  17. memmove(cpu_id, pch2 + 2, strlen(cpuSerial));
  18. break;
  19. }
  20. else
  21. {
  22. return -1;
  23. }
  24. }
  25. }
  26. fclose(fp);
  27. return 0;
  28. }

 3 获取cpu name

无论是X86 linux还是ARM Linux,我们都可以在命令行中使用如下命令得到cpu name,

cat /proc/cpuinfo | grep  model

如果想在代码中实现可以使用如下代码 

  1. int GetCpuInfo(char* cpuName)
  2. {
  3. FILE *fp = fopen("/proc/cpuinfo", "r");
  4. if(NULL == fp)
  5. printf("failed to open cpuinfo\n");
  6. char cpuModel[100] = {0};
  7. while(!feof(fp))
  8. {
  9. memset(cpuModel, 0, sizeof(cpuModel));
  10. fgets(cpuModel, sizeof(cpuModel) - 1, fp); // leave out \n
  11. char* pch = strstr(cpuModel,"model name");
  12. if (pch)
  13. {
  14. char* pch2 = strchr(cpuModel, ':');
  15. if (pch2)
  16. {
  17. memmove(cpuName, pch2 + 2, strlen(cpuModel));
  18. break;
  19. }
  20. else
  21. {
  22. return -1;
  23. }
  24. }
  25. }
  26. fclose(fp);
  27. return 0;
  28. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/136734
推荐阅读
相关标签
  

闽ICP备14008679号