Skip to content

Commit 3400e6d

Browse files
Chris Friedtcfriedt
authored andcommitted
lib: posix: update usleep() to follow the POSIX spec
The original implementation of `usleep()` was not compliant to the POSIX spec in 3 ways. - calling thread may not be suspended (because `k_busy_wait()` was previously used for short durations) - if `usecs` > 1000000, previously we did not return -1 or set `errno` to `EINVAL` - if interrupted, previously we did not return -1 or set `errno` to `EINTR` This change addresses those issues to make `usleep()` more POSIX-compliant. Signed-off-by: Chris Friedt <[email protected]> (cherry picked from commit 7b95428)
1 parent fbea9e7 commit 3400e6d

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

lib/posix/sleep.c

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
* SPDX-License-Identifier: Apache-2.0
55
*/
66

7+
#include <errno.h>
8+
79
#include <kernel.h>
810
#include <posix/unistd.h>
911

@@ -28,10 +30,19 @@ unsigned sleep(unsigned int seconds)
2830
*/
2931
int usleep(useconds_t useconds)
3032
{
31-
if (useconds < USEC_PER_MSEC) {
32-
k_busy_wait(useconds);
33-
} else {
34-
k_msleep(useconds / USEC_PER_MSEC);
33+
int32_t rem;
34+
35+
if (useconds >= USEC_PER_SEC) {
36+
errno = EINVAL;
37+
return -1;
38+
}
39+
40+
rem = k_usleep(useconds);
41+
__ASSERT_NO_MSG(rem >= 0);
42+
if (rem > 0) {
43+
/* sleep was interrupted by a call to k_wakeup() */
44+
errno = EINTR;
45+
return -1;
3546
}
3647

3748
return 0;

0 commit comments

Comments
 (0)