Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // task: get CPU count without /proc or /sys
- // solution: get CPU affinity mask from PID 1
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <sched.h>
- #include <errno.h>
- size_t get_cpu_count(void) {
- const pid_t ack_pid = 1;
- cpu_set_t * cs = NULL;
- cpu_set_t * cs_t = NULL;
- const size_t alloc_thres = 4096, reallocs_max = 10;
- size_t cs_len = 0, reallocs = 0;
- size_t r = 0, i = 0, k = 0;
- cs_len = alloc_thres;
- cs = malloc(cs_len);
- if (!cs) { return 0; }
- while (reallocs < reallocs_max) {
- CPU_ZERO_S(cs_len, cs);
- if (!sched_getaffinity(ack_pid, cs_len, cs)) { break; }
- if (errno != EINVAL) { goto cs_cleanup; }
- cs_len += alloc_thres;
- cs_t = realloc(cs, cs_len);
- if (!cs_t) { goto cs_cleanup; }
- cs = cs_t;
- reallocs++;
- }
- if (reallocs == reallocs_max) {
- // is it better return 0 instead of this?..
- return CPU_COUNT_S(cs_len, cs);
- }
- k = CPU_COUNT_S(cs_len, cs);
- for (i = 0; i < k; i++) {
- if (CPU_ISSET_S(i, cs_len, cs)) { r++; }
- }
- cs_cleanup:
- if (cs) { free(cs); cs = NULL; }
- return r;
- }
- // #include <sys/sysinfo.h>
- int main(void) {
- // printf("cpu count = %d\n", get_nprocs_conf());
- printf("cpu count = %ld\n", get_cpu_count());
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement