22#include <stdio.h>
33#include <stdlib.h>
44#include <string.h>
5+ #include <assert.h>
56
67int get_nproc () {
78 FILE * fp ;
@@ -25,23 +26,20 @@ int get_nproc() {
2526int main () {
2627 FILE * file = fopen ("/proc/stat" , "r" );
2728 char line [1024 ];
28- struct proc_stat stats [get_nproc () + 1 ];
29- int thread_count = 0 ;
30-
31- while (fgets (line , sizeof (line ), file )) {
32- if (strncmp (line , "cpu" , 3 ) == 0 ) {
33- sscanf (line , "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu" ,
34- stats [thread_count ].name , & stats [thread_count ].user ,
35- & stats [thread_count ].nice , & stats [thread_count ].system ,
36- & stats [thread_count ].idle , & stats [thread_count ].iowait ,
37- & stats [thread_count ].irq , & stats [thread_count ].softirq ,
38- & stats [thread_count ].steal , & stats [thread_count ].guest ,
39- & stats [thread_count ].guest_nice );
40- thread_count ++ ;
41- }
29+ int nproc = get_nproc () + 1 ;
30+ struct proc_stat stats [nproc ];
31+
32+ for (int thread = 0 ; thread < nproc ; thread ++ ) {
33+ fgets (line , sizeof (line ), file );
34+ assert (strncmp (line , "cpu" , 3 ) == 0 );
35+ sscanf (line , "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu" ,
36+ stats [thread ].name , & stats [thread ].user , & stats [thread ].nice ,
37+ & stats [thread ].system , & stats [thread ].idle , & stats [thread ].iowait ,
38+ & stats [thread ].irq , & stats [thread ].softirq , & stats [thread ].steal ,
39+ & stats [thread ].guest , & stats [thread ].guest_nice );
4240 }
4341
44- for (int i = 0 ; i < thread_count ; i ++ ) {
42+ for (int i = 0 ; i < nproc ; i ++ ) {
4543 printf ("%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n" , stats [i ].name ,
4644 stats [i ].user , stats [i ].nice , stats [i ].system , stats [i ].idle ,
4745 stats [i ].iowait , stats [i ].irq , stats [i ].softirq , stats [i ].steal ,
0 commit comments