logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

sleep.c (1164B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include "../lib/strtodur.h"
  6. #include <errno.h> // errno
  7. #include <stdio.h> // fprintf, perror
  8. #include <time.h> // nanosleep
  9. int
  10. main(int argc, char *argv[])
  11. {
  12. struct timespec dur = {.tv_sec = 0, .tv_nsec = 0};
  13. for(int i = 1; i < argc; i++)
  14. {
  15. struct timespec arg_dur = {.tv_sec = 0, .tv_nsec = 0};
  16. if(strtodur(argv[i], &arg_dur) < 0)
  17. {
  18. return 1;
  19. }
  20. dur.tv_sec += arg_dur.tv_sec;
  21. dur.tv_nsec += arg_dur.tv_nsec;
  22. if(dur.tv_nsec > 999999999)
  23. {
  24. dur.tv_nsec = 0;
  25. dur.tv_sec += 1;
  26. }
  27. }
  28. if(dur.tv_sec == 0 && dur.tv_nsec == 0)
  29. {
  30. fprintf(stderr, "sleep: error: Got a total duration of 0\n");
  31. return 1;
  32. }
  33. errno = 0;
  34. if(nanosleep(&dur, &dur) < 0)
  35. {
  36. if(errno == EINTR)
  37. {
  38. fprintf(stderr,
  39. "sleep: warning: Interrupted during sleep, still had %ld.%09ld seconds remaining\n",
  40. dur.tv_sec,
  41. dur.tv_nsec);
  42. }
  43. else
  44. {
  45. perror("sleep: warning: nanosleep");
  46. }
  47. }
  48. return 0;
  49. }