3
0

sleep.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. { "", 0 }
  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. char *pp;
  48. int len = strspn(arg, "0123456789.");
  49. char sv = arg[len];
  50. arg[len] = '\0';
  51. errno = 0;
  52. d = strtod(arg, &pp);
  53. if (errno || *pp)
  54. bb_show_usage();
  55. arg[len] = sv;
  56. len--;
  57. sv = arg[len];
  58. arg[len] = '1';
  59. duration += d * xatoul_sfx(&arg[len], sfx);
  60. arg[len] = sv;
  61. } else
  62. duration += xatoul_sfx(arg, sfx);
  63. } while (*++argv);
  64. ts.tv_sec = MAXINT(typeof(ts.tv_sec));
  65. ts.tv_nsec = 0;
  66. if (duration >= 0 && duration < ts.tv_sec) {
  67. ts.tv_sec = duration;
  68. ts.tv_nsec = (duration - ts.tv_sec) * 1000000000;
  69. }
  70. do {
  71. errno = 0;
  72. nanosleep(&ts, &ts);
  73. } while (errno == EINTR);
  74. #elif ENABLE_FEATURE_FANCY_SLEEP
  75. duration = 0;
  76. do {
  77. duration += xatou_range_sfx(*argv, 0, UINT_MAX - duration, sfx);
  78. } while (*++argv);
  79. sleep(duration);
  80. #else /* simple */
  81. duration = xatou(*argv);
  82. sleep(duration);
  83. // Off. If it's really needed, provide example why
  84. //if (sleep(duration)) {
  85. // bb_perror_nomsg_and_die();
  86. //}
  87. #endif
  88. return EXIT_SUCCESS;
  89. }