| 1 | #include <assert.h> |
| 2 | #include <ctype.h> |
| 3 | #include <errno.h> |
| 4 | #include <signal.h> |
| 5 | #include <stdio.h> |
| 6 | #include <stdlib.h> |
| 7 | #include <string.h> |
| 8 | #include <time.h> |
| 9 | #include <unistd.h> |
| 10 | |
| 11 | #include "khatus_lib_log.h" |
| 12 | #include "khatus_lib_time.h" |
| 13 | |
| 14 | #define usage(...) {print_usage(); fprintf(stderr, "Error:\n " __VA_ARGS__); exit(EXIT_FAILURE);} |
| 15 | |
| 16 | #define MAX_LEN 20 |
| 17 | #define END_OF_MESSAGE '\n' |
| 18 | |
| 19 | char *argv0 = NULL; |
| 20 | |
| 21 | double opt_interval = 1.0; |
| 22 | char *opt_fmt = "%a %b %d %H:%M:%S"; |
| 23 | |
| 24 | void |
| 25 | print_usage() |
| 26 | { |
| 27 | printf( |
| 28 | "%s: [OPT ...]\n" |
| 29 | "\n" |
| 30 | "OPT = -i int # interval\n" |
| 31 | " | -f string # format string\n" |
| 32 | " | -h # help message (i.e. what you're reading now :) )\n", |
| 33 | argv0); |
| 34 | } |
| 35 | |
| 36 | void |
| 37 | opt_parse(int argc, char **argv) |
| 38 | { |
| 39 | char c; |
| 40 | |
| 41 | while ((c = getopt(argc, argv, "f:i:h")) != -1) |
| 42 | switch (c) { |
| 43 | case 'f': |
| 44 | opt_fmt = calloc(strlen(optarg), sizeof(char)); |
| 45 | strcpy(opt_fmt, optarg); |
| 46 | break; |
| 47 | case 'i': |
| 48 | opt_interval = atof(optarg); |
| 49 | break; |
| 50 | case 'h': |
| 51 | print_usage(); |
| 52 | exit(EXIT_SUCCESS); |
| 53 | case '?': |
| 54 | if (optopt == 'f' || optopt == 'i') |
| 55 | fprintf(stderr, |
| 56 | "Option -%c requires an argument.\n", |
| 57 | optopt); |
| 58 | else if (isprint(optopt)) |
| 59 | fprintf (stderr, |
| 60 | "Unknown option `-%c'.\n", |
| 61 | optopt); |
| 62 | else |
| 63 | fprintf(stderr, |
| 64 | "Unknown option character `\\x%x'.\n", |
| 65 | optopt); |
| 66 | exit(EXIT_FAILURE); |
| 67 | default: |
| 68 | assert(0); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | int |
| 73 | main(int argc, char **argv) |
| 74 | { |
| 75 | argv0 = argv[0]; |
| 76 | |
| 77 | time_t t; |
| 78 | struct timespec ti; |
| 79 | char buf[MAX_LEN]; |
| 80 | |
| 81 | opt_parse(argc, argv); |
| 82 | ti = timespec_of_float(opt_interval); |
| 83 | debug("opt_fmt: \"%s\"\n", opt_fmt); |
| 84 | debug("opt_interval: %f\n", opt_interval); |
| 85 | debug("ti: {tv_sec = %ld, tv_nsec = %ld}\n", ti.tv_sec, ti.tv_nsec); |
| 86 | memset(buf, '\0', MAX_LEN); |
| 87 | signal(SIGPIPE, SIG_IGN); |
| 88 | |
| 89 | for (;;) { |
| 90 | t = time(NULL); |
| 91 | strftime(buf, MAX_LEN, opt_fmt, localtime(&t)); |
| 92 | puts(buf); |
| 93 | fflush(stdout); |
| 94 | snooze(&ti); |
| 95 | } |
| 96 | return EXIT_SUCCESS; |
| 97 | } |