|
1 | 1 | #include "reader.h" |
2 | 2 | #include "cputracker.h" |
3 | 3 |
|
4 | | -int get_nproc() { |
5 | | - FILE *fp; |
6 | | - char output[64]; |
7 | | - |
8 | | - fp = popen("nproc", "r"); |
9 | | - if (fp == NULL) { |
10 | | - printf("Reading number of threads failed\n"); |
11 | | - exit(EXIT_FAILURE); |
12 | | - } |
13 | | - |
14 | | - int nproc = 0; |
15 | | - if (fgets(output, sizeof(output) - 1, fp) != NULL) { |
16 | | - sscanf(output, "%d", &nproc); |
| 4 | +int get_nproc(int *nproc) { |
| 5 | + *nproc = sysconf(_SC_NPROCESSORS_ONLN); |
| 6 | + if (*nproc == -1) { |
| 7 | + perror("Reading number of threads failed"); |
| 8 | + return -1; |
17 | 9 | } |
18 | | - |
19 | | - pclose(fp); |
20 | | - return nproc; |
| 10 | + return 0; |
21 | 11 | } |
22 | 12 |
|
23 | 13 | struct proc_stat *get_proc_stats() { |
24 | 14 | FILE *file = fopen("/proc/stat", "r"); |
25 | 15 | char line[1024]; |
26 | 16 | struct proc_stat *stats = malloc(nproc * sizeof(struct proc_stat)); |
27 | | - |
28 | 17 | for (int thread = 0; thread < nproc; thread++) { |
29 | 18 | fgets(line, sizeof(line), file); |
30 | 19 | // assert(strncmp(line, "cpu", 3) == 0); |
31 | 20 | if (strncmp(line, "cpu", 3) != 0) { |
32 | | - printf("Reading thread info failed\n"); |
33 | | - exit(EXIT_FAILURE); |
| 21 | + perror("Reading thread info failed\n"); |
| 22 | + free(stats); |
| 23 | + return NULL; |
34 | 24 | } |
| 25 | + |
35 | 26 | sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", |
36 | 27 | stats[thread].name, &stats[thread].user, &stats[thread].nice, |
37 | 28 | &stats[thread].system, &stats[thread].idle, &stats[thread].iowait, |
|
0 commit comments