11#include "reader.h"
2- #include <stdio.h>
3- #include <stdlib.h>
4- #include <string.h>
5- #include <assert.h>
2+ #include "cputracker.h"
63
74int get_nproc () {
85 FILE * fp ;
@@ -11,7 +8,7 @@ int get_nproc() {
118 fp = popen ("nproc" , "r" );
129 if (fp == NULL ) {
1310 printf ("Reading number of threads failed\n" );
14- exit (1 );
11+ exit (EXIT_FAILURE );
1512 }
1613
1714 int nproc = 0 ;
@@ -23,21 +20,29 @@ int get_nproc() {
2320 return nproc ;
2421}
2522
26- int main () {
23+ struct proc_stat * get_proc_stats () {
2724 FILE * file = fopen ("/proc/stat" , "r" );
2825 char line [1024 ];
29- int nproc = get_nproc () + 1 ;
30- struct proc_stat stats [nproc ];
26+ struct proc_stat * stats = malloc (nproc * sizeof (struct proc_stat ));
3127
3228 for (int thread = 0 ; thread < nproc ; thread ++ ) {
3329 fgets (line , sizeof (line ), file );
34- assert (strncmp (line , "cpu" , 3 ) == 0 );
30+ // assert(strncmp(line, "cpu", 3) == 0);
31+ if (strncmp (line , "cpu" , 3 ) != 0 ) {
32+ printf ("Reading thread info failed\n" );
33+ exit (EXIT_FAILURE );
34+ }
3535 sscanf (line , "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu" ,
3636 stats [thread ].name , & stats [thread ].user , & stats [thread ].nice ,
3737 & stats [thread ].system , & stats [thread ].idle , & stats [thread ].iowait ,
3838 & stats [thread ].irq , & stats [thread ].softirq , & stats [thread ].steal ,
3939 & stats [thread ].guest , & stats [thread ].guest_nice );
4040 }
41+ return stats ;
42+ }
43+
44+ int print_stats () {
45+ struct proc_stat * stats = get_proc_stats ();
4146
4247 for (int i = 0 ; i < nproc ; i ++ ) {
4348 printf ("%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n" , stats [i ].name ,
@@ -46,6 +51,6 @@ int main() {
4651 stats [i ].guest , stats [i ].guest_nice );
4752 }
4853
49- fclose ( file );
54+ free ( stats );
5055 return 0 ;
5156}
0 commit comments