Ensure monotonic time in uSecDiffPeriodicActivityBody

This commit is contained in:
emanuele-f 2020-03-05 17:08:44 +01:00
parent 1c7dabf247
commit c17ddb486e
2 changed files with 15 additions and 20 deletions

View file

@ -478,33 +478,25 @@ void ThreadedActivity::aperiodicActivityBody() {
void ThreadedActivity::uSecDiffPeriodicActivityBody() {
struct timeval begin, end;
u_long usec_diff;
#ifndef PERIODIC_DEBUG
u_long max_duration = periodicity * 1e6;
#endif
while(!isTerminating()) {
gettimeofday(&begin, NULL);
runSystemScript(begin.tv_sec);
gettimeofday(&end, NULL);
usec_diff = (end.tv_sec - begin.tv_sec) * 1e6 + (end.tv_usec - begin.tv_usec);
/* We must guarantee that the "now" time, passed to the script,
* it's monotonically increasing. */
while(end.tv_sec < (begin.tv_sec + periodicity)) {
/* Align to the start of the second to avoid crossing second bounds.
* Alignment only happens if the script hasn't already crossed
* its periodicity bound, otherwise the while is just skipped. */
u_long to_sleep = 1e6 - end.tv_usec;
#ifndef PERIODIC_DEBUG
if(usec_diff < max_duration) {
u_int diff;
//ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s] Sleeping %lu us [%lu/%lu]\n", path, to_sleep, end.tv_sec, (begin.tv_sec + periodicity));
_usleep(to_sleep);
if(periodicity == 1)
/* Align to the start of the second to avoid crossing second bounds */
diff = max_duration - end.tv_usec;
else
diff = max_duration - usec_diff;
_usleep(diff);
} /* else { the script took too long } */
#else
/* ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s()", __FUNCTION__); */
#endif
gettimeofday(&end, NULL);
}
}
}