Skip to content

Commit 5af186b

Browse files
authored
wasip2: Fix implementation of usleep (#652)
Currently `CLOCK_REALTIME` is rejected in `clock_nanosleep`, so use `CLOCK_MONOTONIC` instead.
1 parent 5b3cb49 commit 5af186b

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

libc-bottom-half/cloudlibc/src/libc/unistd/usleep.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99
int usleep(useconds_t useconds) {
1010
struct timespec ts = {.tv_sec = useconds / 1000000,
1111
.tv_nsec = useconds % 1000000 * 1000};
12-
int error = clock_nanosleep(CLOCK_REALTIME, 0, &ts, NULL);
12+
#ifdef __wasilibc_use_wasip2
13+
clockid_t clock_id = CLOCK_MONOTONIC;
14+
#else
15+
clockid_t clock_id = CLOCK_REALTIME;
16+
#endif
17+
int error = clock_nanosleep(clock_id, 0, &ts, NULL);
1318
if (error != 0) {
1419
errno = error;
1520
return -1;

test/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,7 @@ add_wasilibc_test(time.c)
306306
add_wasilibc_test(utime.c FS)
307307
add_wasilibc_test(rewinddir.c FS)
308308
add_wasilibc_test(seekdir.c FS)
309+
add_wasilibc_test(usleep.c)
309310

310311
if (TARGET_TRIPLE MATCHES "-threads")
311312
add_wasilibc_test(busywait.c)

test/src/usleep.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <sys/time.h>
2+
#include <time.h>
3+
#include <errno.h>
4+
#include <stdio.h>
5+
#include <stdlib.h>
6+
#include "test.h"
7+
8+
#define TEST(c) do { \
9+
errno = 0; \
10+
if (!(c)) \
11+
t_error("%s failed (errno = %d)\n", #c, errno); \
12+
} while(0)
13+
14+
int main(void)
15+
{
16+
// Sleep for a total of 5ms
17+
long ns_to_sleep = 5E6;
18+
19+
struct timespec start_time, end_time;
20+
clock_gettime(CLOCK_MONOTONIC, &start_time);
21+
TEST(usleep(ns_to_sleep / 1000) == 0);
22+
clock_gettime(CLOCK_MONOTONIC, &end_time);
23+
TEST(end_time.tv_sec - start_time.tv_sec <= 1);
24+
25+
long nanoseconds_elapsed = (end_time.tv_sec - start_time.tv_sec) * 1E9
26+
- start_time.tv_nsec
27+
+ end_time.tv_nsec;
28+
29+
// Test that the difference between the requested amount of sleep
30+
// and the actual elapsed time is within an acceptable margin
31+
double difference = abs(nanoseconds_elapsed - ns_to_sleep)
32+
/ ns_to_sleep;
33+
34+
// Allow the actual sleep time to be twice as much as the requested time
35+
TEST(difference >= 0 && difference <= 1);
36+
37+
return t_status;
38+
}

0 commit comments

Comments
 (0)