2 * watch -- execute a program repeatedly, displaying output fullscreen
4 * Based on the original 1991 'watch' by Tony Rems <rembo@unisoft.com>
5 * (with mods and corrections by Francois Pinard).
7 * Substantially reworked, new features (differences option, SIGWINCH
8 * handling, unlimited command length, long line handling) added Apr
9 * 1999 by Mike Coleman <mkc@acm.org>.
11 * Changes by Albert Cahalan, 2002-2003.
12 * stderr handling, exec, and beep option added by Morty Abzug, 2008
13 * Unicode Support added by Jarrod Lowe <procps@rrod.net> in 2009.
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
32 #include "fileutils.h"
45 #include <sys/ioctl.h>
52 # define _XOPEN_SOURCE_EXTENDED 1
55 #endif /* WITH_WATCH8BIT */
60 # define isprint(x) ( (x>=' '&&x<='~') || (x>=0xa0) )
64 /* Boolean command line options */
66 #define WATCH_DIFF (1 << 1)
67 #define WATCH_CUMUL (1 << 2)
68 #define WATCH_EXEC (1 << 3)
69 #define WATCH_BEEP (1 << 4)
70 #define WATCH_COLOR (1 << 5)
71 #define WATCH_ERREXIT (1 << 6)
72 #define WATCH_CHGEXIT (1 << 7)
74 static int curses_started = 0;
75 static long height = 24, width = 80;
76 static int screen_size_changed = 0;
77 static int first_screen = 1;
78 static int show_title = 2; /* number of lines used, 2 or 0 */
79 static int precise_timekeeping = 0;
81 #define min(x,y) ((x) > (y) ? (y) : (x))
82 #define MAX_ANSIBUF 100
84 static void __attribute__ ((__noreturn__))
87 fputs(USAGE_HEADER, out);
89 _(" %s [options] command\n"), program_invocation_short_name);
90 fputs(USAGE_OPTIONS, out);
91 fputs(_(" -b, --beep beep if command has a non-zero exit\n"), out);
92 fputs(_(" -c, --color interpret ANSI color and style sequences\n"), out);
93 fputs(_(" -d, --differences[=<permanent>]\n"
94 " highlight changes between updates\n"), out);
95 fputs(_(" -e, --errexit exit if command has a non-zero exit\n"), out);
96 fputs(_(" -g, --chgexit exit when output from command changes\n"), out);
97 fputs(_(" -n, --interval <secs> seconds to wait between updates\n"), out);
98 fputs(_(" -p, --precise attempt run command in precise intervals\n"), out);
99 fputs(_(" -t, --no-title turn off header\n"), out);
100 fputs(_(" -x, --exec pass command to exec instead of \"sh -c\"\n"), out);
101 fputs(USAGE_SEPARATOR, out);
102 fputs(USAGE_HELP, out);
103 fputs(_(" -v, --version output version information and exit\n"), out);
104 fprintf(out, USAGE_MAN_TAIL("watch(1)"));
106 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
109 static int nr_of_colors;
110 static int attributes;
115 static void reset_ansi(void)
117 attributes = A_NORMAL;
122 static void init_ansi_colors(void)
124 short ncurses_colors[] = {
125 -1, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
126 COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
129 nr_of_colors = sizeof(ncurses_colors) / sizeof(short);
131 for (bg_col = 0; bg_col < nr_of_colors; bg_col++)
132 for (fg_col = 0; fg_col < nr_of_colors; fg_col++)
133 init_pair(bg_col * nr_of_colors + fg_col + 1, ncurses_colors[fg_col], ncurses_colors[bg_col]);
138 static int set_ansi_attribute(const int attrib)
141 case -1: /* restore last settings */
143 case 0: /* restore default settings */
146 case 1: /* set bold / increased intensity */
147 attributes |= A_BOLD;
149 case 2: /* set decreased intensity (if supported) */
153 case 3: /* set italic (if supported) */
154 attributes |= A_ITALIC;
157 case 4: /* set underline */
158 attributes |= A_UNDERLINE;
160 case 5: /* set blinking */
161 attributes |= A_BLINK;
163 case 7: /* set inversed */
164 attributes |= A_REVERSE;
166 case 21: /* unset bold / increased intensity */
167 attributes &= ~A_BOLD;
169 case 22: /* unset bold / any intensity modifier */
170 attributes &= ~(A_BOLD | A_DIM);
173 case 23: /* unset italic */
174 attributes &= ~A_ITALIC;
177 case 24: /* unset underline */
178 attributes &= ~A_UNDERLINE;
180 case 25: /* unset blinking */
181 attributes &= ~A_BLINK;
183 case 27: /* unset inversed */
184 attributes &= ~A_REVERSE;
193 if (attrib >= 30 && attrib <= 37) { /* set foreground color */
194 fg_col = attrib - 30 + 1;
195 } else if (attrib >= 40 && attrib <= 47) { /* set background color */
196 bg_col = attrib - 40 + 1;
198 return 0; /* Not understood */
201 attrset(attributes | COLOR_PAIR(bg_col * nr_of_colors + fg_col + 1));
205 static void process_ansi(FILE * fp)
208 char buf[MAX_ANSIBUF];
209 char *numstart, *endptr;
216 for (i = 0; i < MAX_ANSIBUF; i++) {
218 /* COLOUR SEQUENCE ENDS in 'm' */
223 if ((c < '0' || c > '9') && c != ';') {
229 * buf now contains a semicolon-separated list of decimal integers,
230 * each indicating an attribute to apply.
231 * For example, buf might contain "0;1;31", derived from the color
232 * escape sequence "<ESC>[0;1;31m". There can be 1 or more
233 * attributes to apply, but typically there are between 1 and 3.
236 /* Special case of <ESC>[m */
238 set_ansi_attribute(0);
240 for (endptr = numstart = buf; *endptr != '\0'; numstart = endptr + 1) {
241 if (!set_ansi_attribute(strtol(numstart, &endptr, 10)))
246 static void __attribute__ ((__noreturn__)) do_exit(int status)
254 static void die(int notused __attribute__ ((__unused__)))
256 do_exit(EXIT_SUCCESS);
259 static void winch_handler(int notused __attribute__ ((__unused__)))
261 screen_size_changed = 1;
264 static char env_col_buf[24];
265 static char env_row_buf[24];
266 static int incoming_cols;
267 static int incoming_rows;
269 static void get_terminal_size(void)
272 if (!incoming_cols) {
273 /* have we checked COLUMNS? */
274 const char *s = getenv("COLUMNS");
279 t = strtol(s, &endptr, 0);
280 if (!*endptr && 0 < t)
282 width = incoming_cols;
283 snprintf(env_col_buf, sizeof env_col_buf, "COLUMNS=%ld",
288 if (!incoming_rows) {
289 /* have we checked LINES? */
290 const char *s = getenv("LINES");
295 t = strtol(s, &endptr, 0);
296 if (!*endptr && 0 < t)
298 height = incoming_rows;
299 snprintf(env_row_buf, sizeof env_row_buf, "LINES=%ld",
304 if (ioctl(STDERR_FILENO, TIOCGWINSZ, &w) == 0) {
305 if (incoming_cols < 0 || incoming_rows < 0) {
306 if (incoming_rows < 0 && w.ws_row > 0) {
308 snprintf(env_row_buf, sizeof env_row_buf,
309 "LINES=%ld", height);
312 if (incoming_cols < 0 && w.ws_col > 0) {
314 snprintf(env_col_buf, sizeof env_col_buf,
315 "COLUMNS=%ld", width);
322 /* get current time in usec */
323 typedef unsigned long long watch_usec_t;
324 #define USECS_PER_SEC (1000000ull)
325 static watch_usec_t get_time_usec()
328 gettimeofday(&now, NULL);
329 return USECS_PER_SEC * now.tv_sec + now.tv_usec;
332 #ifdef WITH_WATCH8BIT
333 /* read a wide character from a popen'd stream */
334 #define MAX_ENC_BYTES 16
335 wint_t my_getwc(FILE * s);
336 wint_t my_getwc(FILE * s)
338 /* assuming no encoding ever consumes more than 16 bytes */
339 char i[MAX_ENC_BYTES];
346 if (i[byte] == EOF) {
351 mbtowc(NULL, NULL, 0);
352 convert = mbtowc(&rval, i, byte);
355 /* legal conversion */
358 if (byte == MAX_ENC_BYTES) {
360 /* at least *try* to fix up */
361 ungetc(i[--byte], s);
368 #endif /* WITH_WATCH8BIT */
370 #ifdef WITH_WATCH8BIT
371 static void output_header(wchar_t *restrict wcommand, int wcommand_characters, double interval)
373 static void output_header(char *restrict command, double interval)
374 #endif /* WITH_WATCH8BIT */
376 time_t t = time(NULL);
377 char *ts = ctime(&t);
380 int max_host_name_len = (int) sysconf(_SC_HOST_NAME_MAX);
381 char hostname[max_host_name_len + 1];
382 int command_columns = 0; /* not including final \0 */
384 gethostname(hostname, sizeof(hostname));
387 * left justify interval and command, right justify hostname and time,
388 * clipping all to fit window width
390 int hlen = asprintf(&header, _("Every %.1fs: "), interval);
391 int rhlen = asprintf(&right_header, _("%s: %s"), hostname, ts);
395 * width < rhlen : print nothing
396 * width < rhlen + hlen + 1: print hostname, ts
397 * width = rhlen + hlen + 1: print header, hostname, ts
398 * width < rhlen + hlen + 4: print header, ..., hostname, ts
399 * width < rhlen + hlen + wcommand_columns: print header,
400 * truncated wcommand, ..., hostname, ts
401 * width > "": print header, wcomand, hostname, ts
402 * this is slightly different from how it used to be
409 if (rhlen + hlen + 1 <= width) {
410 mvaddstr(0, 0, header);
411 if (rhlen + hlen + 2 <= width) {
412 if (width < rhlen + hlen + 4) {
413 mvaddstr(0, width - rhlen - 4, "... ");
415 #ifdef WITH_WATCH8BIT
416 command_columns = wcswidth(wcommand, -1);
417 if (width < rhlen + hlen + command_columns) {
418 /* print truncated */
419 int available = width - rhlen - hlen;
420 int in_use = command_columns;
421 int wcomm_len = wcommand_characters;
422 while (available - 4 < in_use) {
424 in_use = wcswidth(wcommand, wcomm_len);
426 mvaddnwstr(0, hlen, wcommand, wcomm_len);
427 mvaddstr(0, width - rhlen - 4, "... ");
429 mvaddwstr(0, hlen, wcommand);
432 command_columns = strlen(command);
433 if (width < rhlen + hlen + command_columns) {
434 /* print truncated */
435 mvaddnstr(0, hlen, command, width - rhlen - hlen - 4);
436 mvaddstr(0, width - rhlen - 4, "... ");
438 mvaddnstr(0, hlen, command, width - rhlen - hlen);
440 #endif /* WITH_WATCH8BIT */
444 mvaddstr(0, width - rhlen + 1, right_header);
450 static int run_command(char *restrict command, char **restrict command_argv)
461 if (pipe(pipefd) < 0)
462 xerr(7, _("unable to create IPC pipes"));
464 /* flush stdout and stderr, since we're about to do fd stuff */
468 /* fork to prepare to run command */
471 if (child < 0) { /* fork error */
472 xerr(2, _("unable to fork process"));
473 } else if (child == 0) { /* in child */
474 close(pipefd[0]); /* child doesn't need read side of pipe */
475 close(1); /* prepare to replace stdout with pipe */
476 if (dup2(pipefd[1], 1) < 0) { /* replace stdout with write side of pipe */
477 xerr(3, _("dup2 failed"));
479 close(pipefd[1]); /* once duped, the write fd isn't needed */
480 dup2(1, 2); /* stderr should default to stdout */
482 if (flags & WATCH_EXEC) { /* pass command to exec instead of system */
483 if (execvp(command_argv[0], command_argv) == -1) {
484 xerr(4, _("unable to execute '%s'"),
488 status = system(command); /* watch manpage promises sh quoting */
489 /* propagate command exit status as child exit status */
490 if (!WIFEXITED(status)) { /* child exits nonzero if command does */
493 exit(WEXITSTATUS(status));
498 /* otherwise, we're in parent */
499 close(pipefd[1]); /* close write side of pipe */
500 if ((p = fdopen(pipefd[0], "r")) == NULL)
501 xerr(5, _("fdopen"));
504 for (y = show_title; y < height; y++) {
505 int eolseen = 0, tabpending = 0, tabwaspending = 0;
506 if (flags & WATCH_COLOR)
507 set_ansi_attribute(-1);
508 #ifdef WITH_WATCH8BIT
511 for (x = 0; x < width; x++) {
512 #ifdef WITH_WATCH8BIT
519 if (tabwaspending && (flags & WATCH_COLOR))
520 set_ansi_attribute(-1);
524 /* if there is a tab pending, just
525 * spit spaces until the next stop
526 * instead of reading characters */
528 #ifdef WITH_WATCH8BIT
536 } while (c != WEOF && !iswprint(c)
542 || !(flags & WATCH_COLOR)));
546 while (c != EOF && !isprint(c)
550 || !(flags & WATCH_COLOR)));
552 if (c == L'\033' && (flags & WATCH_COLOR)) {
558 if (!oldeolseen && x == 0) {
565 #ifdef WITH_WATCH8BIT
566 if (x == width - 1 && wcwidth(c) == 2) {
568 x = -1; /* process this double-width */
569 carry = c; /* character on the next line */
570 continue; /* because it won't fit here */
572 if (c == WEOF || c == L'\n' || c == L'\t') {
574 if (flags & WATCH_COLOR)
578 if (c == EOF || c == '\n' || c == '\t') {
580 if (flags & WATCH_COLOR)
584 if (tabpending && (((x + 1) % 8) == 0)) {
591 if (!first_screen && !exit_early && (flags & WATCH_CHGEXIT)) {
592 #ifdef WITH_WATCH8BIT
595 exit_early = (wchar_t) c != oldc.chars[0];
597 chtype oldch = inch();
598 unsigned char oldc = oldch & A_CHARTEXT;
599 exit_early = (unsigned char)c != oldc;
602 if (flags & WATCH_DIFF) {
603 #ifdef WITH_WATCH8BIT
607 && ((wchar_t) c != oldc.chars[0]
609 ((flags & WATCH_CUMUL)
610 && (oldc.attr & A_ATTRIBUTES)));
612 chtype oldch = inch();
613 unsigned char oldc = oldch & A_CHARTEXT;
615 && ((unsigned char)c != oldc
617 ((flags & WATCH_CUMUL)
618 && (oldch & A_ATTRIBUTES)));
623 #ifdef WITH_WATCH8BIT
624 addnwstr((wchar_t *) & c, 1);
630 #ifdef WITH_WATCH8BIT
631 if (wcwidth(c) == 0) {
634 if (wcwidth(c) == 2) {
639 oldeolseen = eolseen;
645 /* harvest child process and get status, propagated from command */
646 if (waitpid(child, &status, 0) < 0)
647 xerr(8, _("waitpid"));
649 /* if child process exited in error, beep if option_beep is set */
650 if ((!WIFEXITED(status) || WEXITSTATUS(status))) {
651 if (flags & WATCH_BEEP)
653 if (flags & WATCH_ERREXIT) {
654 mvaddstr(height - 1, 0,
655 _("command exit with a non-zero status, press a key to exit"));
667 int main(int argc, char *argv[])
673 int command_length = 0; /* not including final \0 */
674 watch_usec_t next_loop; /* next loop time in us, used for precise time
676 #ifdef WITH_WATCH8BIT
677 wchar_t *wcommand = NULL;
678 int wcommand_characters = 0; /* not including final \0 */
679 #endif /* WITH_WATCH8BIT */
681 static struct option longopts[] = {
682 {"color", no_argument, 0, 'c'},
683 {"differences", optional_argument, 0, 'd'},
684 {"help", no_argument, 0, 'h'},
685 {"interval", required_argument, 0, 'n'},
686 {"beep", no_argument, 0, 'b'},
687 {"errexit", no_argument, 0, 'e'},
688 {"chgexit", no_argument, 0, 'g'},
689 {"exec", no_argument, 0, 'x'},
690 {"precise", no_argument, 0, 'p'},
691 {"no-title", no_argument, 0, 't'},
692 {"version", no_argument, 0, 'v'},
696 #ifdef HAVE_PROGRAM_INVOCATION_NAME
697 program_invocation_name = program_invocation_short_name;
699 setlocale(LC_ALL, "");
700 bindtextdomain(PACKAGE, LOCALEDIR);
702 atexit(close_stdout);
705 getopt_long(argc, argv, "+bced::ghn:pvtx", longopts, (int *)0))
712 flags |= WATCH_COLOR;
717 flags |= WATCH_CUMUL;
720 flags |= WATCH_ERREXIT;
723 flags |= WATCH_CHGEXIT;
732 interval = strtod_nol_or_err(optarg, _("failed to parse argument"));
735 if (interval > UINT_MAX)
739 precise_timekeeping = 1;
745 printf(PROCPS_NG_VERSION);
757 command_argv = &(argv[optind]);
759 command = xstrdup(argv[optind++]);
760 command_length = strlen(command);
761 for (; optind < argc; optind++) {
763 int s = strlen(argv[optind]);
765 command = xrealloc(command, command_length + s + 2);
766 endp = command + command_length;
768 memcpy(endp + 1, argv[optind], s);
769 /* space then string length */
770 command_length += 1 + s;
771 command[command_length] = '\0';
774 #ifdef WITH_WATCH8BIT
775 /* convert to wide for printing purposes */
776 /*mbstowcs(NULL, NULL, 0); */
777 wcommand_characters = mbstowcs(NULL, command, 0);
778 if (wcommand_characters < 0) {
779 fprintf(stderr, _("unicode handling error\n"));
783 (wchar_t *) malloc((wcommand_characters + 1) * sizeof(wcommand));
784 if (wcommand == NULL) {
785 fprintf(stderr, _("unicode handling error (malloc)\n"));
788 mbstowcs(wcommand, command, wcommand_characters + 1);
789 #endif /* WITH_WATCH8BIT */
793 /* Catch keyboard interrupts so we can put tty back in a sane
796 signal(SIGTERM, die);
798 signal(SIGWINCH, winch_handler);
800 /* Set up tty for curses use. */
803 if (flags & WATCH_COLOR) {
806 use_default_colors();
809 flags &= ~WATCH_COLOR;
816 if (precise_timekeeping)
817 next_loop = get_time_usec();
820 if (screen_size_changed) {
822 resizeterm(height, width);
824 /* redrawwin(stdscr); */
825 screen_size_changed = 0;
830 #ifdef WITH_WATCH8BIT
831 output_header(wcommand, wcommand_characters, interval);
833 output_header(command, interval);
834 #endif /* WITH_WATCH8BIT */
836 if (run_command(command, command_argv))
840 if (precise_timekeeping) {
841 watch_usec_t cur_time = get_time_usec();
842 next_loop += USECS_PER_SEC * interval;
843 if (cur_time < next_loop)
844 usleep(next_loop - cur_time);
846 if (interval < UINT_MAX / USECS_PER_SEC)
847 usleep(interval * USECS_PER_SEC);