sts.c
changeset 144 f064cd793f8d
child 145 63a5269fb113
equal deleted inserted replaced
143:88d9b8bfa7a5 144:f064cd793f8d
       
     1 /**
       
     2  * sts.c: show time stamp
       
     3  * Copyright (C) 2010 Markus Broeker
       
     4  */
       
     5 
       
     6 #include <stdio.h>
       
     7 #include <stdlib.h>
       
     8 #include <string.h>
       
     9 #include <math.h>
       
    10 #include <time.h>
       
    11 #include <errno.h>
       
    12 
       
    13 void usage (char *name)
       
    14 {
       
    15     printf ("Usage: %s STAMP [BOOT-STAMP]\n", name);
       
    16     exit (EXIT_FAILURE);
       
    17 }
       
    18 
       
    19 time_t parse (char *buf)
       
    20 {
       
    21     time_t sec = 0;
       
    22     time_t milli = 0;
       
    23     double value;
       
    24 
       
    25     if (sscanf (buf, "%ld.%ld", &sec, &milli) != 2) {
       
    26         fprintf (stderr, "  sec: %ld, ", sec);
       
    27         fprintf (stderr, "milli: %ld\n", milli);
       
    28     }
       
    29 
       
    30     value = (milli / 1000000);
       
    31     return sec + (time_t) (floor (value));
       
    32 }
       
    33 
       
    34 time_t getboottime ()
       
    35 {
       
    36     char buf[80];
       
    37     time_t now = time (NULL);
       
    38 
       
    39     FILE *f = fopen ("/proc/uptime", "r");
       
    40     if (fgets (buf, sizeof (buf), f) == NULL) {
       
    41         perror ("FOPEN");
       
    42         exit (errno);
       
    43     }
       
    44 
       
    45     fclose (f);
       
    46     return now - parse (buf);
       
    47 }
       
    48 
       
    49 int main (int argc, char **argv)
       
    50 {
       
    51     time_t boot;
       
    52     time_t stamp = 0;
       
    53     time_t diff;
       
    54 
       
    55     if (argc < 2)
       
    56         usage (argv[0]);
       
    57 
       
    58     stamp = parse (argv[1]);
       
    59 
       
    60     if (argc == 3) {
       
    61         boot = parse (argv[2]);
       
    62     } else
       
    63         boot = getboottime ();
       
    64 
       
    65     diff = boot + stamp;
       
    66     printf ("%s: %s", argv[1], ctime (&diff));
       
    67 
       
    68     return EXIT_SUCCESS;
       
    69 }