Skip to content

Commit 941a652

Browse files
committed
Create reader.c and reader.h
Add proc_stat struct Add the reading from /proc/stat
0 parents  commit 941a652

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
a.out
2+
.vscode/c_cpp_properties.json
3+
.vscode/launch.json
4+
.vscode/settings.json

reader.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
#include <stdlib.h>
4+
#include "reader.h"
5+
6+
int main() {
7+
FILE* file = fopen("/proc/stat", "r");
8+
char line[1024];
9+
struct proc_stat* stats = NULL;
10+
int thread_count = 0;
11+
int capacity = 0;
12+
13+
while (fgets(line, sizeof(line), file)) {
14+
if (strncmp(line, "cpu", 3) == 0) {
15+
if (thread_count == capacity) {
16+
capacity = capacity == 0 ? 1 : capacity * 2;
17+
struct proc_stat* temp = realloc(stats, capacity * sizeof(struct proc_stat));
18+
if(temp == NULL) {
19+
perror("Error reallocating memory");
20+
free(stats);
21+
fclose(file);
22+
return 1;
23+
}
24+
stats = temp;
25+
}
26+
sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", stats[thread_count].name, &stats[thread_count].user, &stats[thread_count].nice, &stats[thread_count].system, &stats[thread_count].idle, &stats[thread_count].iowait, &stats[thread_count].irq, &stats[thread_count].softirq, &stats[thread_count].steal, &stats[thread_count].guest, &stats[thread_count].guest_nice);
27+
thread_count++;
28+
}else{
29+
break;
30+
}
31+
}
32+
33+
for (int i = 0; i < thread_count; i++) {
34+
printf("%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n", stats[i].name, stats[i].user, stats[i].nice, stats[i].system, stats[i].idle, stats[i].iowait, stats[i].irq, stats[i].softirq, stats[i].steal, stats[i].guest, stats[i].guest_nice);
35+
}
36+
37+
free(stats);
38+
fclose(file);
39+
return 0;
40+
}

reader.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
struct proc_stat {
3+
char name[256];
4+
unsigned long user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
5+
};

0 commit comments

Comments
 (0)