Skip to content

Commit 46d489c

Browse files
add error checking for Linux get_cpu_time()
1 parent 8f6e800 commit 46d489c

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

lib/procinfo.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ extern double process_tree_cpu_time(int pid);
8383
// get the CPU time of the given process and its descendants
8484

8585
extern double total_cpu_time();
86-
// total CPU time, as reported by OS
86+
// total user-mode CPU time, as reported by OS
8787

8888
extern double boinc_related_cpu_time(PROC_MAP&, bool using_vbox);
8989
// total CPU of current BOINC processes, low-priority processes,

lib/procinfo_unix.cpp

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,14 +273,25 @@ double total_cpu_time() {
273273
static double scale;
274274
if (!f) {
275275
f = fopen("/proc/stat", "r");
276+
if (!f) {
277+
fprintf(stderr, "can't open /proc/stat\n");
278+
return 0;
279+
}
276280
long hz = sysconf(_SC_CLK_TCK);
277281
scale = 1./hz;
278282
} else {
279283
fflush(f);
280284
rewind(f);
281285
}
282-
if (!fgets(buf, 256, f)) return 0;
286+
if (!fgets(buf, 256, f)) {
287+
fprintf(stderr, "can't read /proc/stat\n");
288+
return 0;
289+
}
283290
double user, nice;
284-
sscanf(buf, "cpu %lf %lf", &user, &nice);
291+
int n = sscanf(buf, "cpu %lf %lf", &user, &nice);
292+
if (n != 2) {
293+
fprintf(stderr, "can't parse /proc/stat: %s\n", buf);
294+
return 0;
295+
}
285296
return (user+nice)*scale;
286297
}

0 commit comments

Comments
 (0)