blob: b783d34deb9405020e452fd205e77bf81b56fac1 [file] [log] [blame]
Glenn L McGrath18b76e62002-09-16 09:10:04 +00001/* 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 *
Rob Landley399d2b52006-05-25 23:02:40 +00007 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Glenn L McGrath18b76e62002-09-16 09:10:04 +00008 */
9
Manuel Novoa III cad53642003-03-19 09:13:01 +000010/* BB_AUDIT SUSv3 N/A */
11/* BB_AUDIT GNU defects -- only option -n is supported. */
12
13/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
14 *
15 * Removed dependency on date_main(), added proper error checking, and
16 * reduced size.
17 */
Glenn L McGrath18b76e62002-09-16 09:10:04 +000018
19#include <stdio.h>
Glenn L McGrath18b76e62002-09-16 09:10:04 +000020#include <stdlib.h>
21#include <string.h>
Manuel Novoa III cad53642003-03-19 09:13:01 +000022#include <limits.h>
23#include <time.h>
24#include <assert.h>
25#include <unistd.h>
Eric Andersen29f9b2f2002-12-11 04:25:02 +000026#include <sys/wait.h>
Glenn L McGrath18b76e62002-09-16 09:10:04 +000027#include "busybox.h"
28
Rob Landleydfba7412006-03-06 20:47:33 +000029int watch_main(int argc, char **argv)
Glenn L McGrath18b76e62002-09-16 09:10:04 +000030{
Rob Landley399d2b52006-05-25 23:02:40 +000031 int width, len;
Manuel Novoa III cad53642003-03-19 09:13:01 +000032 unsigned period = 2;
Rob Landley399d2b52006-05-25 23:02:40 +000033 char **watched_argv, *header;
Glenn L McGrath18b76e62002-09-16 09:10:04 +000034
Rob Landley399d2b52006-05-25 23:02:40 +000035 if (argc < 2) bb_show_usage();
36
37 get_terminal_width_height(1, &width, 0);
38 header = xzalloc(width--);
Glenn L McGrath18b76e62002-09-16 09:10:04 +000039
Manuel Novoa III cad53642003-03-19 09:13:01 +000040 /* don't use getopt, because it permutes the arguments */
41 ++argv;
Rob Landley399d2b52006-05-25 23:02:40 +000042 if ((argc > 3) && !strcmp(*argv, "-n")) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000043 period = bb_xgetularg10_bnd(argv[1], 1, UINT_MAX);
44 argv += 2;
45 }
46 watched_argv = argv;
Glenn L McGrath18b76e62002-09-16 09:10:04 +000047
48 /* create header */
Glenn L McGrath18b76e62002-09-16 09:10:04 +000049
Rob Landley399d2b52006-05-25 23:02:40 +000050 len = snprintf(header, width, "Every %ds:", period);
51 while (*argv && len<width)
52 snprintf(header+len, width-len, " %s", *(argv++));
Glenn L McGrath18b76e62002-09-16 09:10:04 +000053
54 while (1) {
Rob Landley399d2b52006-05-25 23:02:40 +000055 char *thyme;
56 time_t t;
Glenn L McGrath18b76e62002-09-16 09:10:04 +000057
Rob Landley399d2b52006-05-25 23:02:40 +000058 time(&t);
59 thyme = ctime(&t);
60 len = strlen(thyme);
61 if (len < width) header[width-len] = 0;
62
63 printf("\033[H\033[J%s %s\n", header, thyme);
64
65 waitpid(bb_xspawn(watched_argv),0,0);
66 sleep(period);
Glenn L McGrath18b76e62002-09-16 09:10:04 +000067 }
Glenn L McGrath18b76e62002-09-16 09:10:04 +000068}