watch: shrink (by walter harms <WHarms AT bfs.de>)

watch_main                                           327     263     -64
This commit is contained in:
Denis Vlasenko 2008-02-24 14:33:17 +00:00
parent 400d8bb45e
commit 28b29916cb

View File

@ -28,46 +28,40 @@ int watch_main(int argc, char **argv)
{ {
unsigned opt; unsigned opt;
unsigned period = 2; unsigned period = 2;
unsigned cmdlen; int width, new_width;
char *header = NULL; char *header;
char *cmd; char *cmd;
char *tmp;
char **p;
opt_complementary = "-1"; // at least one param please opt_complementary = "-1:n+"; // at least one param; -n NUM
opt = getopt32(argv, "+dtn:", &tmp); // "+": stop at first non-option (procps 3.x only)
//if (opt & 0x1) // -d (ignore) opt = getopt32(argv, "+dtn:", &period);
//if (opt & 0x2) // -t
if (opt & 0x4) period = xatou(tmp);
argv += optind; argv += optind;
p = argv; // watch from both procps 2.x and 3.x does concatenation. Example:
cmdlen = 1; // 1 for terminal NUL // watch ls -l "a /tmp" "2>&1" -- ls won't see "a /tmp" as one param
while (*p) cmd = *argv;
cmdlen += strlen(*p++) + 1; while (*++argv)
tmp = cmd = xmalloc(cmdlen); cmd = xasprintf("%s %s", cmd, *argv); // leaks cmd
while (*argv) {
tmp += sprintf(tmp, " %s", *argv);
argv++;
}
cmd++; // skip initial space
width = -1; // make sure first time new_width != width
header = NULL;
while (1) { while (1) {
printf("\033[H\033[J"); printf("\033[H\033[J");
if (!(opt & 0x2)) { // no -t if (!(opt & 0x2)) { // no -t
int width, len; const int time_len = sizeof("1234-67-90 23:56:89");
char *thyme;
time_t t; time_t t;
get_terminal_width_height(STDIN_FILENO, &width, 0); get_terminal_width_height(STDIN_FILENO, &new_width, NULL);
header = xrealloc(header, width--); if (new_width != width) {
// '%-*s' pads header with spaces to the full width width = new_width;
snprintf(header, width, "Every %ds: %-*s", period, width, cmd); free(header);
header = xasprintf("Every %us: %-*s", period, width, cmd);
}
time(&t); time(&t);
thyme = ctime(&t); if (time_len < width)
len = strlen(thyme); strftime(header + width - time_len, time_len,
if (len < width) "%Y-%m-%d %H:%M:%S", localtime(&t));
strcpy(header + width - len, thyme);
puts(header); puts(header);
} }
fflush(stdout); fflush(stdout);