Home | History | Annotate | Download | only in pending
      1 /* watch.c - Execute a program periodically
      2  *
      3  * Copyright 2013 Sandeep Sharma <sandeep.jack2756 (at) gmail.com>
      4  * Copyright 2013 Kyungwan Han <asura321 (at) gmail.com>
      5  *
      6 USE_WATCH(NEWTOY(watch, "^<1n#<0=2te", TOYFLAG_USR|TOYFLAG_BIN))
      7 
      8 config WATCH
      9   bool "watch"
     10   default n
     11   help
     12     usage: watch [-n SEC] [-t] PROG ARGS
     13 
     14     Run PROG periodically
     15 
     16     -n  Loop period in seconds (default 2)
     17     -t  Don't print header
     18     -e  Freeze updates on command error, and exit after enter.
     19 */
     20 #define FOR_watch
     21 #include "toys.h"
     22 
     23 GLOBALS(
     24   int interval;
     25 )
     26 
     27 void watch_main(void)
     28 {
     29   int i = 0, hlen;
     30   time_t t;
     31   unsigned width = 80, len = sizeof("Www Mmm dd hh:mm:ss yyyy") - 1 ;
     32   char *header, *cmd = *toys.optargs;
     33   int retval;
     34 
     35   while(toys.optargs[++i])
     36   {
     37     char * oldcmd = cmd;
     38     cmd = xmprintf("%s %s", oldcmd, toys.optargs[i]);
     39     if (CFG_TOYBOX_FREE) free(oldcmd);
     40   }
     41   header = xmprintf("Every %us: %s", TT.interval, cmd);
     42   hlen = strlen(header);
     43 
     44   while(1) {
     45     xprintf("\033[H\033[J");
     46     if(!(toys.optflags & FLAG_t)) {
     47       terminal_size(&width, NULL);
     48       if (!width) width = 80; //on serial it may return 0.
     49       time(&t);
     50       if (width > (hlen + len)) xprintf("%s", header);
     51       if(width >= len)
     52         xprintf("%*s\n",width + ((width > (hlen + len))?-hlen:0) + 1, ctime(&t));
     53       else
     54         xprintf("\n\n");
     55     }
     56     fflush(NULL); //making sure the screen is clear
     57     retval = system(cmd);
     58     if ((toys.optflags & FLAG_e) && retval){
     59       xprintf("command exit with non-zero status, press enter to exit\n");
     60       getchar();
     61       break;
     62     }
     63     sleep(TT.interval);
     64   }
     65 
     66   if (CFG_TOYBOX_FREE){
     67     free(header);
     68     if (cmd != *toys.optargs) free(cmd);
     69   }
     70 }
     71