Skip to content

Instantly share code, notes, and snippets.

@brb

brb/main.c

Created Jan 31, 2019
Embed
What would you like to do?
bpf_num_possible_cpus
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
static inline unsigned int bpf_num_possible_cpus(void)
{
static const char *fcpu = "/tmp/foo";
unsigned int start, end, possible_cpus = 0;
char buff[128];
FILE *fp;
int n, i, j = 0;
fp = fopen(fcpu, "r");
if (!fp) {
printf("Failed to open %s: '%s'!\n", fcpu, strerror(errno));
exit(1);
}
if (!fgets(buff, sizeof(buff), fp)) {
printf("Failed to read %s!\n", fcpu);
exit(1);
}
int len = strlen(buff);
for (i = 0; i <= len; i++) {
if (buff[i] == ',' || buff[i] == '\0') {
buff[i] = '\0';
n = sscanf(&buff[j], "%u-%u", &start, &end);
if (n <= 0) {
printf("Failed to retrieve # possible CPUs!\n");
exit(1);
} else if (n == 1) {
end = start;
}
possible_cpus += end - start + 1;
j = i + 1;
}
}
fclose(fp);
return possible_cpus;
}
int main()
{
printf("num: %d\n", bpf_num_possible_cpus());
return 0;
}
$ echo -n "" > /tmp/foo && ./main
Failed to read /tmp/foo!
$ echo "" > /tmp/foo && ./main
Failed to retrieve # possible CPUs!
$ echo "1" > /tmp/foo && ./main
num: 1
$ echo "1,3" > /tmp/foo && ./main
num: 2
$ echo "0,2-3" > /tmp/foo && ./main
num: 3
$ echo "0-1,3-4" > /tmp/foo && ./main
num: 4
$ echo "0-3" > /tmp/foo && ./main
num: 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment