如何在C中的任何Linux发行版上解析/ proc / cpuinfo

时间:2015-07-30 10:51:31

标签: c linux ubuntu fread cpu-cores

我正在运行Ubuntu而且我不明白为什么我在C系统中获取内核数量这么难!我已经尝试在运行Ubuntu的系统上成功解析/proc/cpuinfo,但后来我尝试了另一个运行arch linux的系统,因为缓冲区太小而无法解决,我似乎无法弄清楚如何使它适用于我的两个系统。

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE* fp; 
  char *buffer, *tmp; 
  size_t bytes_read, size; 

  if((fp = fopen("/proc/cpuinfo", "r")) == NULL) {
    perror("open failed");
    exit(EXIT_FAILURE); 
  }
  size = 1024;
  if((buffer = malloc(size)) == NULL) {
    perror("malloc failed");
    free(buffer);
    exit(EXIT_FAILURE);
  }
  while(!feof(fp)) {
    bytes_read = fread(buffer, 1, size, fp);
    if(bytes_read == size) {
      size += 128;
      if((tmp = realloc(buffer, size)) == NULL) {
        perror("realloc failed");
        free(buffer);
        exit(EXIT_FAILURE);
      }else {
        buffer = tmp;
      }
    } 
  }
  fclose(fp); 
  if(bytes_read == 0 || bytes_read == size) {
    perror("read failed or buffer isn't big enough.");
    exit(EXIT_FAILURE); 
  }
  printf("%d bytes read out of %d\n", (int)bytes_read,(int) size);
  buffer[bytes_read] = '\0';

  printf("%s", buffer); 
}

这会输出572 bytes read out of 1152,但只要我再次使用fread,它就会覆盖缓冲区。我无法使用sysconf(_SC_NPROCESSORS_ONLN);,因为它似乎并不适用于Ubuntu。

3 个答案:

答案 0 :(得分:3)

如何使用popen(3)执行cat ^processor /proc/cpuinfo | wc -l来获取CPU的数量,然后从管道中读取结果?它非常简单,您不必维护复杂的代码来读取和解析整个文件。

以下是一个例子:

#include <stdio.h>

int ncpus(void) {
    FILE *cmd = popen("grep '^processor' /proc/cpuinfo | wc -l", "r");

    if (cmd == NULL)
        return -1;

    unsigned nprocs;
    size_t n;
    char buff[8];

    if ((n = fread(buff, 1, sizeof(buff)-1, cmd)) <= 0)
        return -1;

    buff[n] = '\0';
    if (sscanf(buff, "%u", &nprocs) != 1)
        return -1;

    pclose(cmd);

    return nprocs;
}

int main(void) {
    int cpus = ncpus();
    if (cpus == -1)
        fprintf(stderr, "Error retrieving number of CPUs\n");
    else
        printf("Number of CPUs: %d\n", cpus);
    return 0;
}

您可能希望改进ncpus()中的错误处理,使其有点用户友好(现在,如果返回-1,您真的不知道发生了什么)。

<强>更新

如下面评论中所述,nproc(1)可能是更好的选择,至少命令更小。它会以任何方式工作,我们可以用grep替换wc + nproc

答案 1 :(得分:1)

以下是如何获取物理内核和虚拟线程的最小示例:

#include <stdio.h>

...

FILE *cpu_info = fopen("/proc/cpuinfo", "r");
unsigned int thread_count, core_count;
while (!fscanf(cpu_info, "siblings\t: %u", &thread_count))
  fscanf(cpu_info, "%*[^s]");
while (!fscanf(cpu_info, "cpu cores\t: %u", &core_count))                   
  fscanf(cpu_info, "%*[^c]");                                                                                          
fclose(cpu_info);

请注意,在此示例中,您无需检查 EOF,因为如果达到,fscanf 将返回 EOF。这将导致循环安全停止。

此外,此示例不包含错误检查以查看 fopen 是否失败。这应该按照您认为合适的方式进行。

fscanf 技术源自此处:https://stackoverflow.com/a/43483850

答案 2 :(得分:0)

这是旧问题,但是如果有人遇到同样的问题。该代码也适用于bigLITTLE处理器。

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include<map>
#include<cstring>
using namespace std;

int main() {
    map <string,int > cpu_count;
    map <string,float > freq_count;
    string line;
    string temp="";
    ifstream finfo("/proc/cpuinfo");
    while(getline(finfo,line)) {
        stringstream str(line);
        string itype;
        string info;
        stringstream str1(line);
        string itype1;
        string info1;
        
        if ( getline( str, itype, ':' ) && getline(str,info) && itype.substr(0,10) == "model name" ) {
            cpu_count[info]++;
            temp=info;  
        }

        if ( getline( str1, itype1, ':' ) && getline(str1,info1) && (itype1.substr(0,7) == "cpu MHz" || itype1.substr(0,8) == "BogoMIPS") ) {
            float freq = stof(info1);
            freq_count[temp]+=freq;
        }
    }

    map<string, int>::iterator it1;
    map<string, float>::iterator it2;
    it2=freq_count.begin();
    for (it1 = cpu_count.begin(); it1 != cpu_count.end(); it1++)
    {
        cout << "CPU Model : "<<it1->first << " | Cores : " << it1->second << " | Average Frequency :  " <<it2->second/it1->second<<endl;
        it2++;
    }
    return 0;
}

输出

CPU型号:Intel(R)Core™i7-8750H CPU @ 2.20GHz |芯数:12 |平均频率:808.687