twatch.c - watch - minimalist watch program
HTML git clone git://src.adamsgaard.dk/watch
DIR Log
DIR Files
DIR Refs
DIR LICENSE
---
twatch.c (2566B)
---
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <getopt.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <stdarg.h>
7
8 #define VERSION "0.2.0"
9 #define CMD_MAX_LEN 45
10
11 static int interval = 5;
12
13 static void
14 usage()
15 {
16 printf("%s: %s [OPTIONS] COMMAND\n"
17 "will repeatedly run COMMAND every %d seconds.\n"
18 "Following OPTIONS are valid:\n"
19 " -v show version\n"
20 " -n SECONDS set interval between command invocations\n"
21 " -r N repeat for N times and then quit\n"
22 " -q suppress output (stdout) from COMMAND\n"
23 " -c do not clear screen between COMMAND calls\n"
24 " -- do not consider any following args as options\n"
25 ,
26 __func__, getprogname(), interval);
27 }
28
29 static void
30 die(const char *errstr,...)
31 {
32 va_list ap;
33
34 va_start(ap, errstr);
35 vfprintf(stderr, errstr, ap);
36 va_end(ap);
37 exit(1);
38 }
39
40 static void
41 run_cmd(int sleeptime, char *command, int quiet, int clearscreen)
42 {
43 if (!quiet) {
44 if (clearscreen)
45 printf("\e[1;1H\e[2J"); /* clear screen (POSIX) */
46 else
47 puts("");
48 printf("Every %ds: %s\n\n", sleeptime, command);
49 }
50 if (quiet)
51 strcat(command, " >/dev/null");
52 system(command);
53 sleep(sleeptime);
54 }
55
56 int
57 main(int argc, char *argv[])
58 {
59 int i, opt;
60 int repeat = 0, quiet = 0, clearscreen = 1;
61 char command[CMD_MAX_LEN] = "";
62
63 while ((opt = getopt(argc, argv, "hvn:r:qc")) != -1) {
64 switch (opt) {
65 case -1: /* no more arguments */
66 case 0: /* long options toggles */
67 break;
68 case 'h':
69 usage();
70 return 0;
71 break;
72 case 'v':
73 die("%s " VERSION "\n", argv[0]);
74 break;
75 case 'n':
76 interval = atoi(optarg);
77 break;
78 case 'r':
79 repeat = atoi(optarg);
80 break;
81 case 'q':
82 quiet = 1;
83 break;
84 case 'c':
85 clearscreen = 0;
86 break;
87 default:
88 fprintf(stderr, "%s: invalid option -- %c\n", argv[0], opt);
89 fprintf(stderr, "try `%s --help` for more information\n",
90 argv[0]);
91 return -2;
92 }
93 }
94 argc -= optind;
95 argv += optind;
96
97 if (argc < 1)
98 die("error: no COMMAND specified\n");
99
100 strcat(command, "[ -f ~/.profile ] && . ~/.profile; ");
101 for (i = 0; i < argc; ++i) {
102 if (strlen(command) + strlen(argv[i]) +
103 (i > 0 && i < argc - 1 ? 1 : 0) >= CMD_MAX_LEN)
104 die("error: command length exceeded\n");
105
106 strcat(command, argv[i]);
107 if (i > 0 && i < argc - 1)
108 strcat(command, " ");
109 }
110
111 if (repeat > 0) {
112 for (i = 0; i < repeat; ++i)
113 run_cmd(interval, command, quiet, clearscreen);
114 } else {
115 for (;;)
116 run_cmd(interval, command, quiet, clearscreen);
117 }
118 return 0;
119 }