duration.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2018 Denys Vlasenko
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. //config:config FLOAT_DURATION
  10. //config: bool "Enable fractional duration arguments"
  11. //config: default y
  12. //config: help
  13. //config: Allow sleep N.NNN, top -d N.NNN etc.
  14. //kbuild:lib-$(CONFIG_SLEEP) += duration.o
  15. //kbuild:lib-$(CONFIG_TOP) += duration.o
  16. //kbuild:lib-$(CONFIG_TIMEOUT) += duration.o
  17. //kbuild:lib-$(CONFIG_PING) += duration.o
  18. //kbuild:lib-$(CONFIG_PING6) += duration.o
  19. //kbuild:lib-$(CONFIG_WATCH) += duration.o
  20. #include "libbb.h"
  21. static const struct suffix_mult duration_suffixes[] ALIGN_SUFFIX = {
  22. { "s", 1 },
  23. { "m", 60 },
  24. { "h", 60*60 },
  25. { "d", 24*60*60 },
  26. { "", 0 }
  27. };
  28. #if ENABLE_FLOAT_DURATION
  29. duration_t FAST_FUNC parse_duration_str(char *str)
  30. {
  31. duration_t duration;
  32. if (strchr(str, '.')) {
  33. double d;
  34. char *pp;
  35. int len = strspn(str, "0123456789.");
  36. char sv = str[len];
  37. str[len] = '\0';
  38. errno = 0;
  39. d = strtod(str, &pp);
  40. if (errno || *pp)
  41. bb_show_usage();
  42. str += len;
  43. *str-- = sv;
  44. sv = *str;
  45. *str = '1';
  46. duration = d * xatoul_sfx(str, duration_suffixes);
  47. *str = sv;
  48. } else {
  49. duration = xatoul_sfx(str, duration_suffixes);
  50. }
  51. return duration;
  52. }
  53. void FAST_FUNC sleep_for_duration(duration_t duration)
  54. {
  55. struct timespec ts;
  56. ts.tv_sec = MAXINT(typeof(ts.tv_sec));
  57. ts.tv_nsec = 0;
  58. if (duration >= 0 && duration < ts.tv_sec) {
  59. ts.tv_sec = duration;
  60. ts.tv_nsec = (duration - ts.tv_sec) * 1000000000;
  61. }
  62. do {
  63. errno = 0;
  64. nanosleep(&ts, &ts);
  65. } while (errno == EINTR);
  66. }
  67. #else
  68. duration_t FAST_FUNC parse_duration_str(char *str)
  69. {
  70. return xatou_range_sfx(str, 0, UINT_MAX, duration_suffixes);
  71. }
  72. #endif