watch.c 2.0 KB

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