blob: c275f3bb3cf6f931f77a566f1f054983ba0504ea [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 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 */
22
23/* getopt not needed */
24
25#include <stdio.h>
26#include <errno.h>
27#include <unistd.h>
28#include <stdlib.h>
29#include <string.h>
Eric Andersen29f9b2f2002-12-11 04:25:02 +000030#include <sys/wait.h>
Glenn L McGrath18b76e62002-09-16 09:10:04 +000031#include "busybox.h"
32
33extern int watch_main(int argc, char **argv)
34{
35 const char date_argv[2][10] = { "date", "" };
Glenn L McGrath18b76e62002-09-16 09:10:04 +000036 const int header_len = 40;
37 char header[header_len + 1];
38 int period = 2;
39 char **cargv;
40 int cargc;
41 pid_t pid;
42 int old_stdout;
43 int i;
44
45 if (argc < 2) {
46 show_usage();
47 } else {
48 cargv = argv + 1;
49 cargc = argc - 1;
50
51 /* don't use getopt, because it permutes the arguments */
52 if (argc >= 3 && !strcmp(argv[1], "-n")) {
53 period = strtol(argv[2], NULL, 10);
54 if (period < 1)
55 show_usage();
56 cargv += 2;
57 cargc -= 2;
58 }
59 }
60
61
62 /* create header */
63 snprintf(header, header_len, "Every %ds: ", period);
64 for (i = 0; i < cargc && (strlen(header) + strlen(cargv[i]) < header_len);
65 i++) {
66 strcat(header, cargv[i]);
67 strcat(header, " ");
68 }
69
70 /* fill with blanks */
71 for (i = strlen(header); i < header_len; i++)
72 header[i] = ' ';
73
74 header[header_len - 1] = '\0';
75
76
77 /* thanks to lye, who showed me how to redirect stdin/stdout */
78 old_stdout = dup(1);
79
80 while (1) {
Eric Andersen60943c52002-09-17 20:53:41 +000081 printf("\033[H\033[J%s", header);
Glenn L McGrath18b76e62002-09-16 09:10:04 +000082 date_main(1, (char **) date_argv);
83 printf("\n");
84
85 pid = vfork(); /* vfork, because of ucLinux */
86 if (pid > 0) {
87 //parent
88 wait(0);
89 sleep(period);
90 } else if (0 == pid) {
91 //child
92 close(1);
93 dup(old_stdout);
94 if (execvp(*cargv, cargv))
95 error_msg_and_die("Couldn't run command\n");
96 } else {
97 error_msg_and_die("Couldn't vfork\n");
98 }
99 }
100
101
102 return EXIT_SUCCESS;
103}