Defend against race condition calculating job cpu usage

Closes #7066
This commit is contained in:
Mahmoud Al-Qudsi 2020-05-30 15:59:44 -05:00
parent f4ae69a905
commit 821525e503

View File

@ -32,13 +32,18 @@ static int cpu_use(const job_t *j) {
for (const process_ptr_t &p : j->processes) {
struct timeval t;
int jiffies;
unsigned long jiffies;
gettimeofday(&t, nullptr);
jiffies = proc_get_jiffies(p.get());
double t1 = 1000000.0 * p->last_time.tv_sec + p->last_time.tv_usec;
double t2 = 1000000.0 * t.tv_sec + t.tv_usec;
// Check for a race condition that can cause negative CPU usage to be reported (#7066)
if (t2 < t1 || jiffies < p->last_jiffies) {
continue;
}
// std::fwprintf( stderr, L"t1 %f t2 %f p1 %d p2 %d\n", t1, t2, jiffies, p->last_jiffies );
u += (static_cast<double>(jiffies - p->last_jiffies)) / (t2 - t1);
}