diff --git a/include/zephyr/posix/time.h b/include/zephyr/posix/time.h index 85cb7f8ae4226ae..26e1659320cc773 100644 --- a/include/zephyr/posix/time.h +++ b/include/zephyr/posix/time.h @@ -88,6 +88,7 @@ int clock_gettime(clockid_t clock_id, struct timespec *ts); __syscall int clock_gettime(clockid_t clock_id, struct timespec *ts); #endif /* CONFIG_ARCH_POSIX */ int clock_settime(clockid_t clock_id, const struct timespec *ts); +int clock_getcpuclockid(pid_t pid, clockid_t *clock_id); /* Timer APIs */ int timer_create(clockid_t clockId, struct sigevent *evp, timer_t *timerid); int timer_delete(timer_t timerid); diff --git a/lib/posix/clock.c b/lib/posix/clock.c index d7ca3969aa8631e..ba2bff35129a1af 100644 --- a/lib/posix/clock.c +++ b/lib/posix/clock.c @@ -195,3 +195,28 @@ int gettimeofday(struct timeval *tv, void *tz) return res; } + +/** + * @brief Get current real time. + * + * See IEEE 1003.1 + */ +int clock_getcpuclockid(pid_t pid, clockid_t *clock_id) +{ + /* We don't allow any process ID but our own. */ + if (pid != 0 && pid != getpid()) + return EPERM; + +#ifdef CLOCK_MONOTONIC + *clock_id = CLOCK_MONOTONIC; + return 0; +#else +#ifdef CLOCK_REALTIME + *clock_id = CLOCK_REALTIME; + return 0; +#endif +#endif + + /* We don't have a timer for that. */ + return ENOENT; +} diff --git a/tests/posix/common/src/clock.c b/tests/posix/common/src/clock.c index 154fa6c8da075d0..7f59d8994c0ccd8 100644 --- a/tests/posix/common/src/clock.c +++ b/tests/posix/common/src/clock.c @@ -14,8 +14,10 @@ ZTEST(posix_apis, test_clock) { + int ret; int64_t nsecs_elapsed, secs_elapsed; struct timespec ts, te; + clockid_t clock_id; printk("POSIX clock APIs\n"); @@ -40,6 +42,12 @@ ZTEST(posix_apis, test_clock) zassert_equal(secs_elapsed, SLEEP_SECONDS, "POSIX clock API test failed"); + ret = clock_getcpuclockid(0, &clock_id); + zassert_equal(ret, 0, "POSIX clock_getcpuclock id failed"); + + ret = clock_getcpuclockid((pid_t)2482, &clock_id); + zassert_equal(ret, EPERM, "POSIX clock_getcpuclock id failed"); + printk("POSIX clock APIs test done\n"); }