[libc-commits] [libc] [libc] Implement sleep and usleep for Linux (PR #213912)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Thu Aug 6 00:09:21 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);
----------------
labath wrote:

I have to disagree with that, for a couple of reasons:
- none of the other libc implementations does that
- POSIX isn't particularly specific about this, but it does *not* say that one has to positively be able to identify a signal interruption. It just says to 'return value shall be the "unslept" amount'. If we're rounding down (like other implementations do), then that unslept amount can round to zero.
- I can imagine this breaking (livelocking) loops like `while ((remaining = sleep(remaining) > 0);` if it keeps getting interrupted, e.g. by a setitimer. (Of course, that code is pretty buggy to begin with as the recurring signal would cause it to sleep way less than the intended amount of time -- which is why I think that any serious user will use another sleeping primitive)

https://github.com/llvm/llvm-project/pull/213912


More information about the libc-commits mailing list