/* ncpus.c - find number of CPUs on a Solaris machine * Andrew Ho (andrew@zeuscat.com) * * Displays the number of CPUs on the local machine; works at least on * Solaris systems, where its output should agree with the output of * psrinfo(1). Compile with -DDEBUG to get some debug output when * walking the kstat(3) struct. * * Build: gcc -Wall -lkstat -o ncpus ncpus.c * Usage: ncpus */ #include #include #include #include #include #include #include #include #include #define ME "ncpus" static kstat_ctl_t *kctl = NULL; struct kstat_list { kstat_t *k; struct kstat_list *next; }; int main(int argc, char **argv) { int cpunum, pgsize, ncpu = 0; kstat_t *k; struct kstat_list *cpu = NULL, *cpucur, *newone; /* Open the kstat interface */ pgsize = sysconf(_SC_PAGESIZE); pgsize /= 1024; /* Page size in kb */ if(NULL == (kctl = kstat_open())) { perror("kstat"); exit(1); } for(k = kctl->kc_chain; k; k = k->ks_next) { #ifdef DEBUG printf("%s [debug]: statistic = \"%s\"\n", ME, k->ks_name); #endif if(!strncmp(k->ks_name, "cpu_stat", 8)) { #ifdef DEBUG printf("%s [debug]: found CPU statistic = \"%s\"\n", ME, k->ks_name); #endif (void)sscanf(k->ks_name, "cpu_stat%d", &cpunum); newone = (struct kstat_list *)malloc(sizeof(struct kstat_list)); newone->k = k; newone->next = NULL; if(NULL == cpu) { cpu = newone; cpucur = newone; } else { cpucur->next = newone; cpucur = newone; } ncpu++; } } printf("%s: found %d CPU%s\n", ME, ncpu, ncpu == 1 ? "" : "s"); return 0; }