How to parse /proc/cpuinfo on any linux distro in C -


i running ubuntu , don't understand why it's hard me number of cores on system in c! i've tried parsing /proc/cpuinfo success on system running ubuntu tried on system running arch linux fail because buffer small, , can't seem figure out how make work on both of systems.

#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);  } 

this outputs 572 bytes read out of 1152, overwrites buffer whenever use fread again. , can't use sysconf(_sc_nprocessors_onln); either because doesn't work on ubuntu seems.

how using popen(3) execute cat ^processor /proc/cpuinfo | wc -l count of cpus , read result pipe? it's quite easy, , won't have maintain complicated code read , parse entire file.

here's example:

#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; } 

you might want improve error handling in ncpus() little bit user-friendly (right now, don't know happened if if returns -1).

update

as mentioned below in comments, nproc(1) might better choice here, @ least command smaller. work either way, can replace grep + wc nproc.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -