When I use cat /proc/stat
command on terminal I get the following output:
cpu 9268738 47123 3940054 3851366876 911347 0 164981 0 0 0
cpu0 558436 2170 208965 240825151 54221 0 30439 0 0 0
cpu1 699380 1976 382320 240476662 50707 0 7260 0 0 0
cpu2 547485 2685 204733 240867376 56441 0 4410 0 0 0
cpu3 541016 3581 202538 240872692 57657 0 3051 0 0 0
cpu4 552305 2716 286470 240322626 70098 0 60308 0 0 0
cpu5 490248 3598 211000 240891224 59970 0 2596 0 0 0
cpu6 510708 1987 215605 240879645 57692 0 2546 0 0 0
cpu7 528486 3053 220346 240866189 54916 0 2273 0 0 0
cpu8 540615 2563 216076 240857715 53633 0 2161 0 0 0
cpu9 862775 1794 413426 240049704 49504 0 1755 0 0 0
cpu10 576740 5166 230907 240805093 51594 0 2084 0 0 0
cpu11 611709 2192 268375 240408228 62183 0 37502 0 0 0
cpu12 589948 3351 227945 240734505 59752 0 1992 0 0 0
cpu13 552315 3205 217448 240834143 58786 0 2137 0 0 0
cpu14 554752 3387 218348 240835453 56078 0 2222 0 0 0
cpu15 551815 3693 215547 240840464 58106 0 2240 0 0 0
...
From the aforementioned output I could notice that my computer has 16 distinct CPUs. And I am trying to write a C program to fetch the CPU utilization of all the CPUs cores available. But the issue is that I have the following code, which only enables me to fetch the overall CPU utilization but only reading the first line of the /proc/stat
file:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
long double cpu0_a[4], cpu0_b[4], loadavg;
FILE *fp;
char dump[50];
while(1)
{
fp = fopen("/proc/stat","r");
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&cpu0_a[0],&cpu0_a[1],&cpu0_a[2],&cpu0_a[3]);
fclose(fp);
sleep(1);
fp = fopen("/proc/stat","r");
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&cpu0_b[0],&cpu0_b[1],&cpu0_b[2],&cpu0_b[3]);
fclose(fp);
loadavg = ((cpu0_b[0]+cpu0_b[1]+cpu0_b[2]) - (cpu0_a[0]+cpu0_a[1]+cpu0_a[2])) / ((cpu0_b[0]+cpu0_b[1]+cpu0_b[2]+cpu0_b[3]) - (cpu0_a[0]+cpu0_a[1]+cpu0_a[2]+cpu0_a[3]));
printf("The current CPU utilization is : %Lf\n",loadavg);
}
return(0);
}
How can I read the /proc/stat
file to print out current CPU utilization of all available CPUs individually instead of overall one?
P.S. I am new to C programming and coming from a C# background, so I might be missing something very basic in C. Thank you for your help in this.