nanosleep.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___SUPPORT_IBM_NANOSLEEP_H
  10. #define _LIBCPP___SUPPORT_IBM_NANOSLEEP_H
  11. #include <unistd.h>
  12. inline int nanosleep(const struct timespec* __req, struct timespec* __rem) {
  13. // The nanosleep() function is not available on z/OS. Therefore, we will call
  14. // sleep() to sleep for whole seconds and usleep() to sleep for any remaining
  15. // fraction of a second. Any remaining nanoseconds will round up to the next
  16. // microsecond.
  17. if (__req->tv_sec < 0 || __req->tv_nsec < 0 || __req->tv_nsec > 999999999) {
  18. errno = EINVAL;
  19. return -1;
  20. }
  21. long __micro_sec = (__req->tv_nsec + 999) / 1000;
  22. time_t __sec = __req->tv_sec;
  23. if (__micro_sec > 999999) {
  24. ++__sec;
  25. __micro_sec -= 1000000;
  26. }
  27. __sec = static_cast<time_t>(sleep(static_cast<unsigned int>(__sec)));
  28. if (__sec) {
  29. if (__rem) {
  30. // Updating the remaining time to sleep in case of unsuccessful call to sleep().
  31. __rem->tv_sec = __sec;
  32. __rem->tv_nsec = __micro_sec * 1000;
  33. }
  34. errno = EINTR;
  35. return -1;
  36. }
  37. if (__micro_sec) {
  38. int __rt = usleep(static_cast<unsigned int>(__micro_sec));
  39. if (__rt != 0 && __rem) {
  40. // The usleep() does not provide the amount of remaining time upon its failure,
  41. // so the time slept will be ignored.
  42. __rem->tv_sec = 0;
  43. __rem->tv_nsec = __micro_sec * 1000;
  44. // The errno is already set.
  45. return -1;
  46. }
  47. return __rt;
  48. }
  49. return 0;
  50. }
  51. #endif // _LIBCPP___SUPPORT_IBM_NANOSLEEP_H