3
0

watch.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, char **argv)
  24. {
  25. unsigned opt;
  26. unsigned period = 2;
  27. unsigned cmdlen;
  28. char *header = NULL;
  29. char *cmd;
  30. char *tmp;
  31. char **p;
  32. opt_complementary = "-1"; // at least one param please
  33. opt = getopt32(argv, "+dtn:", &tmp);
  34. //if (opt & 0x1) // -d (ignore)
  35. //if (opt & 0x2) // -t
  36. if (opt & 0x4) period = xatou(tmp);
  37. argv += optind;
  38. p = argv;
  39. cmdlen = 1; // 1 for terminal NUL
  40. while (*p)
  41. cmdlen += strlen(*p++) + 1;
  42. tmp = cmd = xmalloc(cmdlen);
  43. while (*argv) {
  44. tmp += sprintf(tmp, " %s", *argv);
  45. argv++;
  46. }
  47. cmd++; // skip initial space
  48. while (1) {
  49. printf("\033[H\033[J");
  50. if (!(opt & 0x2)) { // no -t
  51. int width, len;
  52. char *thyme;
  53. time_t t;
  54. get_terminal_width_height(STDIN_FILENO, &width, 0);
  55. header = xrealloc(header, width--);
  56. // '%-*s' pads header with spaces to the full width
  57. snprintf(header, width, "Every %ds: %-*s", period, width, cmd);
  58. time(&t);
  59. thyme = ctime(&t);
  60. len = strlen(thyme);
  61. if (len < width)
  62. strcpy(header + width - len, thyme);
  63. puts(header);
  64. }
  65. fflush(stdout);
  66. // TODO: 'real' watch pipes cmd's output to itself
  67. // and does not allow it to overflow the screen
  68. // (taking into account linewrap!)
  69. system(cmd);
  70. sleep(period);
  71. }
  72. return 0; // gcc thinks we can reach this :)
  73. }