[LTP] [PATCH v3] clock_settime: use POSIX runtime detection for CLOCK_MONOTONIC
Cyril Hrubis
chrubis@suse.cz
Mon May 4 11:07:52 CEST 2026
Hi!
> diff --git a/testcases/open_posix_testsuite/include/clock.h b/testcases/open_posix_testsuite/include/clock.h
> new file mode 100644
> index 0000000000000000000000000000000000000000..221dd38ff34b627aa5f6c07825cd7439cf559c74
> --- /dev/null
> +++ b/testcases/open_posix_testsuite/include/clock.h
> @@ -0,0 +1,77 @@
> +/*
> + * Copyright (c) 2026, Linux Test Project
> + * SPDX-License-Identifier: GPL-2.0-or-later
> + */
> +
> +#ifndef PTS_CLOCK_H
> +#define PTS_CLOCK_H
> +
> +#include <stdio.h>
> +#include <stdlib.h>
> +#include <time.h>
> +#include <unistd.h>
> +
> +static inline int pts_mono_available(void)
> +{
> +#ifdef _POSIX_MONOTONIC_CLOCK
> + if (_POSIX_MONOTONIC_CLOCK > 0)
> + return 1;
> +
> + if (!_POSIX_MONOTONIC_CLOCK && sysconf(_SC_MONOTONIC_CLOCK) > 0)
> + return 1;
> +#endif
> + return 0;
> +}
> +
> +#define PTS_MONO_MAX_RETRIES 3
> +
> +static struct timespec pts_mono_start;
> +
> +static inline int pts_mono_time_start(void)
> +{
> + if (!pts_mono_available()) {
> + static int warned;
> +
> + if (!warned) {
> + printf("CLOCK_MONOTONIC unavailable, test may fail due to clock adjustment\n");
> + warned = 1;
> + }
> + return 0;
> + }
> +
> +#ifdef _POSIX_MONOTONIC_CLOCK
I suppose that this not correct either. If _POSIX_MONOTONIC_CLOCK is set
to -1 the CLOCK_MONOTONIC constant may not be defined.
So we either have to to do
#if _POSIX_MONOTONIC_CLOCK >= 0
or
#ifdef CLOCK_MONOTONIC
> + if (clock_gettime(CLOCK_MONOTONIC, &pts_mono_start) != 0) {
> + perror("clock_gettime(CLOCK_MONOTONIC) failed");
> + return -1;
> + }
> +#endif
> + return 0;
> +}
> +
> +static inline int pts_mono_time_check(unsigned int expected_secs)
> +{
> +#ifdef _POSIX_MONOTONIC_CLOCK
> + if (pts_mono_available()) {
> + struct timespec now;
> + long elapsed;
> +
> + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
> + perror("clock_gettime(CLOCK_MONOTONIC) failed");
> + return -1;
> + }
> +
> + elapsed = now.tv_sec - pts_mono_start.tv_sec;
> +
> + if (labs(elapsed - (long)expected_secs) > 1) {
> + printf("Clock adjustment detected (elapsed %lds, expected ~%us)\n",
> + elapsed, expected_secs);
> + return 1;
> + }
> + return 0;
> + }
> +#endif
> + (void)expected_secs;
> + return 0;
> +}
> +
> +#endif /* PTS_CLOCK_H */
>
> ---
> base-commit: 1d2ea5b042a6c6c169689efebd856583200c564f
> change-id: 20260429-fix_clock_settime_helper-7670708ed94f
>
> Best regards,
> --
> Andrea Cervesato <andrea.cervesato@suse.com>
>
>
> --
> Mailing list info: https://lists.linux.it/listinfo/ltp
--
Cyril Hrubis
chrubis@suse.cz
More information about the ltp
mailing list