How to get the number of CPUs in Linux using C?

后端 未结 8 1687
情歌与酒
情歌与酒 2020-11-29 20:17

Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file...

I\'ve found this implementation using

8条回答
  •  臣服心动
    2020-11-29 20:54

    Another method scanning cpu* directories under sys file system:

    #include
    #include 
    #include 
    #define LINUX_SYS_CPU_DIRECTORY "/sys/devices/system/cpu"
    
    int main() {
       int cpu_count = 0;
       DIR *sys_cpu_dir = opendir(LINUX_SYS_CPU_DIRECTORY);
       if (sys_cpu_dir == NULL) {
           int err = errno;
           printf("Cannot open %s directory, error (%d).\n", LINUX_SYS_CPU_DIRECTORY, strerror(err));
           return -1;
       }
       const struct dirent *cpu_dir;
       while((cpu_dir = readdir(sys_cpu_dir)) != NULL) {
           if (fnmatch("cpu[0-9]*", cpu_dir->d_name, 0) != 0)
           {
              /* Skip the file which does not represent a CPU */
              continue;
           }
           cpu_count++;
       }
       printf("CPU count: %d\n", cpu_count);
       return 0;
    }
    

提交回复
热议问题