aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

watch.c (1550B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #include <errno.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <time.h>
      7 #include <unistd.h>
      8 
      9 #include "util.h"
     10 #include "wexec.h"
     11 
     12 static void
     13 usage(void)
     14 {
     15   eprintf("usage: %s [-t] [-n interval] command\n", argv0);
     16 }
     17 
     18 // ?man watch: execute periodically
     19 // ?man arguments: command
     20 // ?man run a program periodically, showing output fullscreen
     21 int
     22 main(int argc, char *argv[])
     23 {
     24   char            cmd[BUFSIZ];
     25   char           *end;
     26   struct timespec interval = {.tv_sec = 2, .tv_nsec = 0};
     27   float           period;
     28   int             i;
     29 
     30   ARGBEGIN
     31   {
     32     // ?man -t: sort or specify timestamp
     33     case 't':
     34       break;
     35     // ?man -n:str: print line numbers or counts
     36     case 'n':
     37       period = strtof(EARGF(usage()), &end);
     38       if (*end != '\0' || errno != 0)
     39         eprintf("invalid interval\n");
     40       if (period < 0)
     41         period = 0.1f;
     42       interval.tv_sec  = period;
     43       interval.tv_nsec = (period - interval.tv_sec) * 1E9;
     44       break;
     45     default:
     46       usage();
     47   }
     48   ARGEND;
     49 
     50   if (argc < 1)
     51     usage();
     52 
     53   if (strlcpy(cmd, argv[0], sizeof(cmd)) >= sizeof(cmd))
     54     eprintf("command too long\n");
     55   for (i = 1; i < argc; i++) {
     56     if (strlcat(cmd, " ", sizeof(cmd)) >= sizeof(cmd))
     57       eprintf("command too long\n");
     58     if (strlcat(cmd, argv[i], sizeof(cmd)) >= sizeof(cmd))
     59       eprintf("command too long\n");
     60   }
     61 
     62   for (;;) {
     63     printf("\x1b[2J\x1b[H"); /* clear */
     64     fflush(NULL);
     65     wsystem(cmd);
     66     nanosleep(&interval, NULL);
     67   }
     68   return 0;
     69 }