En Linux, es posible que no sea seguro de usar, _SC_NPROCESSORS_ONLN
ya que no forma parte del estándar POSIX y el manual sysconf lo dice tanto. Entonces, existe la posibilidad de que _SC_NPROCESSORS_ONLN
no esté presente:
These values also exist, but may not be standard.
[...]
- _SC_NPROCESSORS_CONF
The number of processors configured.
- _SC_NPROCESSORS_ONLN
The number of processors currently online (available).
Un enfoque simple sería leerlos /proc/stat
o /proc/cpuinfo
contarlos:
#include<unistd.h>
#include<stdio.h>
int main(void)
{
char str[256];
int procCount = -1; // to offset for the first entry
FILE *fp;
if( (fp = fopen("/proc/stat", "r")) )
{
while(fgets(str, sizeof str, fp))
if( !memcmp(str, "cpu", 3) ) procCount++;
}
if ( procCount == -1)
{
printf("Unable to get proc count. Defaulting to 2");
procCount=2;
}
printf("Proc Count:%d\n", procCount);
return 0;
}
Utilizando /proc/cpuinfo
:
#include<unistd.h>
#include<stdio.h>
int main(void)
{
char str[256];
int procCount = 0;
FILE *fp;
if( (fp = fopen("/proc/cpuinfo", "r")) )
{
while(fgets(str, sizeof str, fp))
if( !memcmp(str, "processor", 9) ) procCount++;
}
if ( !procCount )
{
printf("Unable to get proc count. Defaulting to 2");
procCount=2;
}
printf("Proc Count:%d\n", procCount);
return 0;
}
El mismo enfoque en shell usando grep:
grep -c ^processor /proc/cpuinfo
O
grep -c ^cpu /proc/stat # subtract 1 from the result