3
0

sleep.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * sleep implementation for busybox
  4. *
  5. * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. /* BB_AUDIT SUSv3 compliant */
  10. /* BB_AUDIT GNU issues -- fancy version matches except args must be ints. */
  11. /* http://www.opengroup.org/onlinepubs/007904975/utilities/sleep.html */
  12. /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  13. *
  14. * Rewritten to do proper arg and error checking.
  15. * Also, added a 'fancy' configuration to accept multiple args with
  16. * time suffixes for seconds, minutes, hours, and days.
  17. */
  18. #include "libbb.h"
  19. /* This is a NOFORK applet. Be very careful! */
  20. #if ENABLE_FEATURE_FANCY_SLEEP || ENABLE_FEATURE_FLOAT_SLEEP
  21. static const struct suffix_mult sfx[] = {
  22. { "s", 1 },
  23. { "m", 60 },
  24. { "h", 60*60 },
  25. { "d", 24*60*60 },
  26. { }
  27. };
  28. #endif
  29. int sleep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  30. int sleep_main(int argc UNUSED_PARAM, char **argv)
  31. {
  32. #if ENABLE_FEATURE_FLOAT_SLEEP
  33. double duration;
  34. struct timespec ts;
  35. #else
  36. unsigned duration;
  37. #endif
  38. ++argv;
  39. if (!*argv)
  40. bb_show_usage();
  41. #if ENABLE_FEATURE_FLOAT_SLEEP
  42. duration = 0;
  43. do {
  44. char *arg = *argv;
  45. if (strchr(arg, '.')) {
  46. double d;
  47. int len = strspn(arg, "0123456789.");
  48. char sv = arg[len];
  49. arg[len] = '\0';
  50. d = bb_strtod(arg, NULL);
  51. if (errno)
  52. bb_show_usage();
  53. arg[len] = sv;
  54. len--;
  55. sv = arg[len];
  56. arg[len] = '1';
  57. duration += d * xatoul_sfx(&arg[len], sfx);
  58. arg[len] = sv;
  59. } else
  60. duration += xatoul_sfx(arg, sfx);
  61. } while (*++argv);
  62. ts.tv_sec = MAXINT(typeof(ts.tv_sec));
  63. ts.tv_nsec = 0;
  64. if (duration >= 0 && duration < ts.tv_sec) {
  65. ts.tv_sec = duration;
  66. ts.tv_nsec = (duration - ts.tv_sec) * 1000000000;
  67. }
  68. do {
  69. errno = 0;
  70. nanosleep(&ts, &ts);
  71. } while (errno == EINTR);
  72. #elif ENABLE_FEATURE_FANCY_SLEEP
  73. duration = 0;
  74. do {
  75. duration += xatou_range_sfx(*argv, 0, UINT_MAX - duration, sfx);
  76. } while (*++argv);
  77. sleep(duration);
  78. #else /* simple */
  79. duration = xatou(*argv);
  80. sleep(duration);
  81. // Off. If it's really needed, provide example why
  82. //if (sleep(duration)) {
  83. // bb_perror_nomsg_and_die();
  84. //}
  85. #endif
  86. return EXIT_SUCCESS;
  87. }