From 0995e17927c70f32b9ce51d2bc774f7c6ad3c29f Mon Sep 17 00:00:00 2001 From: Huang Qi Date: Mon, 6 Nov 2023 12:22:27 +0800 Subject: [PATCH] sched: Check for zero sleep time and yield CPU if necessary Signed-off-by: Huang Qi --- sched/signal/sig_nanosleep.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/sched/signal/sig_nanosleep.c b/sched/signal/sig_nanosleep.c index 8fca6f9f7b2c0..30e3220fe6d7b 100644 --- a/sched/signal/sig_nanosleep.c +++ b/sched/signal/sig_nanosleep.c @@ -103,6 +103,24 @@ int nxsig_nanosleep(FAR const struct timespec *rqtp, return -EINVAL; } + /* If rqtp is zero, yield CPU and return + * Notice: The behavior of sleep(0) is not defined in POSIX, so there are + * different implementations: + * 1. In Linux, nanosleep(0) will call schedule() to yield CPU: + * https://elixir.bootlin.com/linux/latest/source/kernel/time/ + * hrtimer.c#L2038 + * 2. In BSD, nanosleep(0) will return immediately: + * https://github.com/freebsd/freebsd-src/blob/ + * 475fa89800086718bd9249fd4dc3f862549f1f78/crypto/openssh/ + * openbsd-compat/bsd-misc.c#L243 + */ + + if (rqtp->tv_sec == 0 && rqtp->tv_nsec == 0) + { + sched_yield(); + return OK; + } + /* Get the start time of the wait. Interrupts are disabled to prevent * timer interrupts while we do tick-related calculations before and * after the wait.