3
0

duration.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #include "libbb.h"
  20. static const struct suffix_mult duration_suffixes[] = {
  21. { "s", 1 },
  22. { "m", 60 },
  23. { "h", 60*60 },
  24. { "d", 24*60*60 },
  25. { "", 0 }
  26. };
  27. #if ENABLE_FLOAT_DURATION
  28. duration_t FAST_FUNC parse_duration_str(char *str)
  29. {
  30. duration_t duration;
  31. if (strchr(str, '.')) {
  32. double d;
  33. char *pp;
  34. int len = strspn(str, "0123456789.");
  35. char sv = str[len];
  36. str[len] = '\0';
  37. errno = 0;
  38. d = strtod(str, &pp);
  39. if (errno || *pp)
  40. bb_show_usage();
  41. str += len;
  42. *str-- = sv;
  43. sv = *str;
  44. *str = '1';
  45. duration = d * xatoul_sfx(str, duration_suffixes);
  46. *str = sv;
  47. } else {
  48. duration = xatoul_sfx(str, duration_suffixes);
  49. }
  50. return duration;
  51. }
  52. void FAST_FUNC sleep_for_duration(duration_t duration)
  53. {
  54. struct timespec ts;
  55. ts.tv_sec = MAXINT(typeof(ts.tv_sec));
  56. ts.tv_nsec = 0;
  57. if (duration >= 0 && duration < ts.tv_sec) {
  58. ts.tv_sec = duration;
  59. ts.tv_nsec = (duration - ts.tv_sec) * 1000000000;
  60. }
  61. do {
  62. errno = 0;
  63. nanosleep(&ts, &ts);
  64. } while (errno == EINTR);
  65. }
  66. #else
  67. duration_t FAST_FUNC parse_duration_str(char *str)
  68. {
  69. return xatou_range_sfx(str, 0, UINT_MAX, duration_suffixes);
  70. }
  71. #endif