watch.c 2.0 KB

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