libflow: accommodate Macs

As of today, macOS or OS X still does not implement
clock_nanosleep() according to this project:
https://github.com/ChisholmKyle/PosixMachTiming
This commit is contained in:
Michel Machado 2020-06-23 08:01:52 -04:00
parent 5ac9551d87
commit 9a9e74250d
3 changed files with 45 additions and 33 deletions

View File

@ -6,7 +6,6 @@
#include <float.h>
#include <assert.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include "libflow.h"
@ -205,37 +204,6 @@ static inline int flush_chunk(const struct flow *fw, int fd)
return 0;
}
static void msleep(double wait_ms)
{
struct timespec req;
int ret;
assert(!clock_gettime(CLOCK_MONOTONIC, &req));
/* Add @wait_ms to @req. */
if (wait_ms > 1000) {
time_t sec = wait_ms / 1000;
wait_ms -= sec * 1000;
assert(wait_ms > 0);
req.tv_sec += sec;
}
req.tv_nsec += wait_ms * 1000000;
/* Round @req up. */
if (req.tv_nsec >= 1000000000) {
ldiv_t result = ldiv(req.tv_nsec, 1000000000);
req.tv_sec += result.quot;
req.tv_nsec = result.rem;
}
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
&req, NULL);
} while (ret == EINTR);
assert(ret == 0);
}
/* XXX Avoid duplicate this function, which was copied from libutils.h. */
static inline uint64_t diff_timeval_us(const struct timeval *t1,
const struct timeval *t2)

44
utils.c
View File

@ -179,4 +179,46 @@ int posix_fadvise(int fd, off_t offset, off_t len, int advice)
}
}
#endif /* Apple Macintosh */
#include <unistd.h> /* For usleep(). */
void msleep(double wait_ms)
{
assert(!usleep(wait_ms * 1000));
}
#else
#include <time.h> /* For clock_gettime() and clock_nanosleep(). */
void msleep(double wait_ms)
{
struct timespec req;
int ret;
assert(!clock_gettime(CLOCK_MONOTONIC, &req));
/* Add @wait_ms to @req. */
if (wait_ms > 1000) {
time_t sec = wait_ms / 1000;
wait_ms -= sec * 1000;
assert(wait_ms > 0);
req.tv_sec += sec;
}
req.tv_nsec += wait_ms * 1000000;
/* Round @req up. */
if (req.tv_nsec >= 1000000000) {
ldiv_t result = ldiv(req.tv_nsec, 1000000000);
req.tv_sec += result.quot;
req.tv_nsec = result.rem;
}
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
&req, NULL);
} while (ret == EINTR);
assert(ret == 0);
}
#endif

View File

@ -24,6 +24,8 @@ static inline int64_t delay_ms(const struct timeval *t1,
(t2->tv_usec - t1->tv_usec) / 1000;
}
void msleep(double wait_ms);
const long *ls_my_files(const char *path, long start_at, long end_at);
void print_header(FILE *f, const char *name);