logo

utils-std

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

sleep.c (1194B)


  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. const char *argv0 = "sleep";
  10. int
  11. main(int argc, char *argv[])
  12. {
  13. struct timespec dur = {.tv_sec = 0, .tv_nsec = 0};
  14. for(int i = 1; i < argc; i++)
  15. {
  16. struct timespec arg_dur = {.tv_sec = 0, .tv_nsec = 0};
  17. if(strtodur(argv[i], &arg_dur) < 0)
  18. {
  19. return 1;
  20. }
  21. dur.tv_sec += arg_dur.tv_sec;
  22. dur.tv_nsec += arg_dur.tv_nsec;
  23. if(dur.tv_nsec > 999999999)
  24. {
  25. dur.tv_nsec = 0;
  26. dur.tv_sec += 1;
  27. }
  28. }
  29. if(dur.tv_sec == 0 && dur.tv_nsec == 0)
  30. {
  31. fprintf(stderr, "sleep: error: Got a total duration of 0\n");
  32. return 1;
  33. }
  34. errno = 0;
  35. if(nanosleep(&dur, &dur) < 0)
  36. {
  37. if(errno == EINTR)
  38. {
  39. fprintf(stderr,
  40. "sleep: warning: Interrupted during sleep, still had %ld.%09ld seconds remaining\n",
  41. dur.tv_sec,
  42. dur.tv_nsec);
  43. }
  44. else
  45. {
  46. perror("sleep: warning: nanosleep");
  47. }
  48. }
  49. return 0;
  50. }