11#include "fastfetch.h"
22#include "detection/cpuusage/cpuusage.h"
3+ #include "common/io/io.h"
34
45#include <stdio.h>
56#include <inttypes.h>
67
78const char * ffGetCpuUsageInfo (uint64_t * inUseAll , uint64_t * totalAll )
89{
9- uint64_t user = 0 , nice = 0 , system = 0 , idle = 0 , iowait = 0 , irq = 0 , softirq = 0 ;
10-
11- FILE * procStat = fopen ("/proc/stat" , "r" );
10+ FF_AUTO_CLOSE_FILE FILE * procStat = fopen ("/proc/stat" , "r" );
1211 if (procStat == NULL )
1312 {
1413 #ifdef __ANDROID__
@@ -17,16 +16,21 @@ const char* ffGetCpuUsageInfo(uint64_t* inUseAll, uint64_t* totalAll)
1716 return "fopen(\"" "/proc/stat\", \"r\") == NULL" ;
1817 #endif
1918 }
19+ // Skip first line
20+ if (fscanf (procStat , "cpu%*[^\n]\n" ) < 0 )
21+ return "fscanf() first line failed" ;
22+
23+ * inUseAll = 0 ;
24+ * totalAll = 0 ;
2025
21- if (fscanf (procStat , "cpu%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 , & user , & nice , & system , & idle , & iowait , & irq , & softirq ) < 0 )
26+ uint64_t user = 0 , nice = 0 , system = 0 , idle = 0 , iowait = 0 , irq = 0 , softirq = 0 ;
27+ while (fscanf (procStat , "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 , & user , & nice , & system , & idle , & iowait , & irq , & softirq ) == 7 )
2228 {
23- fclose (procStat );
24- return "fscanf() failed" ;
29+ uint64_t inUse = user + nice + system ;
30+ uint64_t total = inUse + idle + iowait + irq + softirq ;
31+ * inUseAll += inUse ;
32+ * totalAll += total ;
2533 }
26- * inUseAll = user + nice + system ;
27- * totalAll = * inUseAll + idle + iowait + irq + softirq ;
28-
29- fclose (procStat );
3034
3135 return NULL ;
3236}
0 commit comments