watch.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini watch implementation for busybox
  4. *
  5. * Copyright (C) 2001 by Michael Habermann <mhabermann@gmx.de>
  6. * Copyrigjt (C) Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  9. */
  10. /* BB_AUDIT SUSv3 N/A */
  11. /* BB_AUDIT GNU defects -- only option -n is supported. */
  12. #include "libbb.h"
  13. // procps 2.0.18:
  14. // watch [-d] [-n seconds]
  15. // [--differences[=cumulative]] [--interval=seconds] command
  16. //
  17. // procps-3.2.3:
  18. // watch [-dt] [-n seconds]
  19. // [--differences[=cumulative]] [--interval=seconds] [--no-title] command
  20. //
  21. // (procps 3.x and procps 2.x are forks, not newer/older versions of the same)
  22. int watch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  23. int watch_main(int argc UNUSED_PARAM, char **argv)
  24. {
  25. unsigned opt;
  26. unsigned period = 2;
  27. unsigned width, new_width;
  28. char *header;
  29. char *cmd;
  30. opt_complementary = "-1:n+"; // at least one param; -n NUM
  31. // "+": stop at first non-option (procps 3.x only)
  32. opt = getopt32(argv, "+dtn:", &period);
  33. argv += optind;
  34. // watch from both procps 2.x and 3.x does concatenation. Example:
  35. // watch ls -l "a /tmp" "2>&1" -- ls won't see "a /tmp" as one param
  36. cmd = *argv;
  37. while (*++argv)
  38. cmd = xasprintf("%s %s", cmd, *argv); // leaks cmd
  39. width = (unsigned)-1; // make sure first time new_width != width
  40. header = NULL;
  41. while (1) {
  42. printf("\033[H\033[J");
  43. if (!(opt & 0x2)) { // no -t
  44. const unsigned time_len = sizeof("1234-67-90 23:56:89");
  45. time_t t;
  46. get_terminal_width_height(STDIN_FILENO, &new_width, NULL);
  47. if (new_width != width) {
  48. width = new_width;
  49. free(header);
  50. header = xasprintf("Every %us: %-*s", period, (int)width, cmd);
  51. }
  52. time(&t);
  53. if (time_len < width)
  54. strftime(header + width - time_len, time_len,
  55. "%Y-%m-%d %H:%M:%S", localtime(&t));
  56. puts(header);
  57. }
  58. fflush(stdout);
  59. // TODO: 'real' watch pipes cmd's output to itself
  60. // and does not allow it to overflow the screen
  61. // (taking into account linewrap!)
  62. system(cmd);
  63. sleep(period);
  64. }
  65. return 0; // gcc thinks we can reach this :)
  66. }