aboutsummaryrefslogtreecommitdiff
path: root/coreutils/watch.c
blob: b1a7d90861fc53037ea68c14e9551cfaaeb2b27b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* vi: set sw=4 ts=4: */
/*
 * Mini watch implementation for busybox
 *
 * Copyright (C) 2001 by Michael Habermann <mhabermann@gmx.de>
 * Copyrigjt (C) Mar 16, 2003 Manuel Novoa III   (mjn3@codepoet.org)
 *
 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
 */

/* BB_AUDIT SUSv3 N/A */
/* BB_AUDIT GNU defects -- only option -n is supported. */

#include "busybox.h"


int watch_main(int argc, char **argv)
{
	int width, len;
	unsigned period = 2;
	char **watched_argv, *header;

	if (argc < 2) bb_show_usage();

	get_terminal_width_height(STDOUT_FILENO, &width, 0);
	header = xzalloc(width--);

	/* don't use getopt, because it permutes the arguments */
	++argv;
	if ((argc > 3) && argv[0][0] == '-' && argv[0][1] == 'n') {
		period = xatou(argv[1]);
		argv += 2;
	}
	watched_argv = argv;

	/* create header */
	len = snprintf(header, width, "Every %ds:", period);
	while (*argv && len<width)
		snprintf(header+len, width-len, " %s", *(argv++));

	while (1) {
		char *thyme;
		time_t t;

		time(&t);
		thyme = ctime(&t);
		len = strlen(thyme);
		if (len < width)
			header[width-len] = 0;
		bb_printf("\033[H\033[J%s %s\n", header, thyme);

		waitpid(xspawn(watched_argv),0,0);
		sleep(period);
	}
	if (ENABLE_FEATURE_CLEAN_UP)
		free(header);
}