slstatus.c (2163B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <errno.h> 3 #include <signal.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <time.h> 8 9 #include "arg.h" 10 #include "slstatus.h" 11 #include "util.h" 12 13 struct arg { 14 const char *(*func)(const char *); 15 const char *fmt; 16 const char *args; 17 }; 18 19 char buf[1024]; 20 static volatile sig_atomic_t done; 21 22 #include "config.h" 23 24 static void 25 terminate(const int signo) 26 { 27 if (signo != SIGUSR1) 28 done = 1; 29 } 30 31 static void 32 difftimespec(struct timespec *res, struct timespec *a, struct timespec *b) 33 { 34 res->tv_sec = a->tv_sec - b->tv_sec - (a->tv_nsec < b->tv_nsec); 35 res->tv_nsec = a->tv_nsec - b->tv_nsec + 36 (a->tv_nsec < b->tv_nsec) * 1E9; 37 } 38 39 static void 40 usage(void) 41 { 42 die("usage: %s [-v] [-s] [-1]", argv0); 43 } 44 45 int 46 main(int argc, char *argv[]) 47 { 48 struct sigaction act; 49 struct timespec start, current, diff, intspec, wait; 50 size_t i, len; 51 int ret; 52 char status[MAXLEN]; 53 const char *res; 54 55 ARGBEGIN { 56 case 'v': 57 die("swstatus-"VERSION); 58 break; 59 case '1': 60 done = 1; 61 break; 62 case 's': 63 break; 64 default: 65 usage(); 66 } ARGEND 67 68 if (argc) 69 usage(); 70 71 memset(&act, 0, sizeof(act)); 72 act.sa_handler = terminate; 73 sigaction(SIGINT, &act, NULL); 74 sigaction(SIGTERM, &act, NULL); 75 act.sa_flags |= SA_RESTART; 76 sigaction(SIGUSR1, &act, NULL); 77 78 do { 79 if (clock_gettime(CLOCK_MONOTONIC, &start) < 0) 80 die("clock_gettime:"); 81 82 status[0] = '\0'; 83 for (i = len = 0; i < LEN(args); i++) { 84 if (!(res = args[i].func(args[i].args))) 85 res = unknown_str; 86 87 if ((ret = esnprintf(status + len, sizeof(status) - len, 88 args[i].fmt, res)) < 0) 89 break; 90 91 len += ret; 92 } 93 94 if (puts(status) == EOF || fflush(stdout) == EOF) 95 die("stdout:"); 96 97 if (!done) { 98 if (clock_gettime(CLOCK_MONOTONIC, ¤t) < 0) 99 die("clock_gettime:"); 100 difftimespec(&diff, ¤t, &start); 101 102 intspec.tv_sec = interval / 1000; 103 intspec.tv_nsec = (interval % 1000) * 1E6; 104 difftimespec(&wait, &intspec, &diff); 105 106 if (wait.tv_sec >= 0 && 107 nanosleep(&wait, NULL) < 0 && 108 errno != EINTR) 109 die("nanosleep:"); 110 } 111 } while (!done); 112 113 return 0; 114 }