[libc-commits] [libc] [libc] Implement sleep and usleep for Linux (PR #213912)
Jeff Bailey via libc-commits
libc-commits at lists.llvm.org
Wed Aug 5 01:54:32 PDT 2026
================
@@ -0,0 +1,36 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Linux implementation of sleep.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/unistd/sleep.h"
+#include "hdr/types/struct_timespec.h"
+#include "hdr/types/time_t.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/nanosleep.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(unsigned int, sleep, (unsigned int seconds)) {
+ static_assert(sizeof(unsigned int) <= sizeof(time_t), "Avoids overflow");
+ struct timespec req = {seconds, 0};
+ struct timespec rem = {};
+ ErrorOr<int> result = linux_syscalls::nanosleep(&req, &rem);
+ if (!result) {
+ // Cast does not lose information as `remaining` cannot be greater than
+ // `seconds`.
+ return static_cast<unsigned int>(rem.tv_sec);
----------------
kaladron wrote:
Minor nit, but this ensures that we don't return 0 if the result is non-zero because of an interruption:
```suggestion
return static_cast<unsigned int>(rem.tv_sec + (rem.tv_nsec > 0 ? 1 : 0));
}
```
This could happen is sleeping 1s but interrupted after 100ms.
https://github.com/llvm/llvm-project/pull/213912
More information about the libc-commits
mailing list