Skip to content

Commit 3050213

Browse files
committed
Change printf to perror
Add exitcode to get_nproc
1 parent 334d1f6 commit 3050213

File tree

4 files changed

+19
-27
lines changed

4 files changed

+19
-27
lines changed

cputracker.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
#include "cputracker.h"
22
#include "reader.h"
3+
#include <stdlib.h>
34

45
int nproc = 0;
56

6-
int main(){
7-
nproc = get_nproc() + 1;
7+
int main() {
8+
if (get_nproc(&nproc) == -1)
9+
exit(EXIT_FAILURE);
810

9-
print_stats();
10-
return 0;
11+
print_stats();
12+
return 0;
1113
}

cputracker.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#ifndef CPUTRACKER_H
2-
#define CPUTRACKER_H
2+
#define CPUTRACKER_H
33

44
#include <assert.h>
55
#include <stdio.h>
@@ -9,7 +9,6 @@
99
#define EXIT_FAILURE 1
1010
#define EXIT_SUCCESS 0
1111

12-
1312
extern int nproc;
1413

1514
struct proc_stat {

reader.c

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,28 @@
11
#include "reader.h"
22
#include "cputracker.h"
33

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;
179
}
18-
19-
pclose(fp);
20-
return nproc;
10+
return 0;
2111
}
2212

2313
struct proc_stat *get_proc_stats() {
2414
FILE *file = fopen("/proc/stat", "r");
2515
char line[1024];
2616
struct proc_stat *stats = malloc(nproc * sizeof(struct proc_stat));
27-
2817
for (int thread = 0; thread < nproc; thread++) {
2918
fgets(line, sizeof(line), file);
3019
// assert(strncmp(line, "cpu", 3) == 0);
3120
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;
3424
}
25+
3526
sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
3627
stats[thread].name, &stats[thread].user, &stats[thread].nice,
3728
&stats[thread].system, &stats[thread].idle, &stats[thread].iowait,

reader.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#ifndef READER_H
2-
#define READER_H
3-
2+
#define READER_H
3+
#include <unistd.h>
44

55
int print_stats();
66
struct proc_stat *get_proc_stats();

0 commit comments

Comments
 (0)