Как вы уже продемонстрировали в своем последующем ответе, вам нужно перебрать строки вывода.
Но, чтобы перебрать все имеющиеся процессоры, не зная общего количества, вы можете просто определить структуру C,и создать его с произвольным (большим) числом.
Я адаптировал нечто подобное, что я сделал для вашего примера, так что результат будет другим, но в качестве примера достаточно.
(Не проверено очень хорошо, может иметь некоторые очевидные логические дыры, но, опять же, пример)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/*
outputs CPU utilization for up to MAX_CPU CPUs.
* To output only the individual CPUs and not the combined total, set SKIP_TOTAL to 1
* To output only the combined total, set SKIP_TOTAL to 0, and MAX_CPU to 0
*/
#define MAX_CPU 64 // arbitrary max; can be set to 0 to only output overall
#define SKIP_TOTAL 1 // skips first "cpu", set to 0 to include in output
struct CPUS {
char id[4];
long double user;
long double nice;
long double system;
long double idle;
long double idle_last; // store previous idle value
long double sum_last; // store previous sum value
};
struct CPUS cpus[MAX_CPU + 1];
void calculate(int output) {
long cpu_delta, cpu_idle, cpu_used, utilization;
FILE *fp;
int last_cpu = 0;
int cpu_num = 0;
int sum;
fp = fopen("/proc/stat", "r");
while (last_cpu == 0 && cpu_num <= MAX_CPU) {
fscanf(
fp, "%s %Lf %Lf %Lf %Lf%*[^\n]\n",
(char *)&cpus[cpu_num].id, &cpus[cpu_num].user, &cpus[cpu_num].nice,
&cpus[cpu_num].system, &cpus[cpu_num].idle
);
// check if the first colum (placed in the id field) contains "cpu", if
// not, we are no longer processing CPU related lines
if(strstr(cpus[cpu_num].id, "cpu") != NULL) {
if (cpu_num == 0) {
if (SKIP_TOTAL == 1) {
cpu_num += 1;
continue;
} else {
// overwrite "cpu" to "all"
strcpy(cpus[cpu_num].id, "all");
}
}
// sum all of the values
sum = cpus[cpu_num].user + cpus[cpu_num].nice + \
cpus[cpu_num].system + cpus[cpu_num].idle;
// collect the difference between sum and the last sum
cpu_delta = sum - cpus[cpu_num].sum_last;
// collect idle time
cpu_idle = cpus[cpu_num].idle - cpus[cpu_num].idle_last;
// delta minus ide time
cpu_used = cpu_delta - cpu_idle;
// percentage of utilization
utilization = (100 * cpu_used) / cpu_delta;
if (output == 1) {
printf("%s:\t%li%%\n", cpus[cpu_num].id, utilization);
}
// store the current sum and idle time for calculation on next iteration
cpus[cpu_num].sum_last = sum;
cpus[cpu_num].idle_last = cpus[cpu_num].idle;
} else {
// no more CPUs to enumarte; exit while loop
last_cpu = 1;
}
cpu_num += 1;
}
fclose(fp);
}
int main(void) {
calculate(0); // first pass to collect baseline (no output)
usleep(200*1000); // wait
calculate(1); // collect again and output
return 0;
}