sts.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Nov 2010 04:05:14 +0100
changeset 153 b223089872b6
parent 145 63a5269fb113
child 156 2898369b1cdc
permissions -rw-r--r--
ipv6 support added committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * sts.c: show time stamp
 * Copyright (C) 2010 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>

void usage (char *name)
{
    printf ("Usage: %s STAMP [BOOT-STAMP]\n", name);
    exit (EXIT_FAILURE);
}

time_t parse (char *buf)
{
    time_t sec = 0;
    time_t milli = 0;

    if (sscanf (buf, "%ld.%ld", &sec, &milli) != 2) {
        fprintf (stderr, "  sec: %ld, ", sec);
        fprintf (stderr, "milli: %ld\n", milli);
    }

    return sec;
}

time_t getboottime ()
{
    char buf[80];
    time_t now = time (NULL);

    FILE *f = fopen ("/proc/uptime", "r");
    if (fgets (buf, sizeof (buf), f) == NULL) {
        perror ("FOPEN");
        exit (errno);
    }

    fclose (f);
    return now - parse (buf);
}

int main (int argc, char **argv)
{
    time_t boot;
    time_t stamp = 0;
    time_t diff;

    if (argc < 2)
        usage (argv[0]);

    stamp = parse (argv[1]);

    if (argc == 3) {
        boot = parse (argv[2]);
    } else
        boot = getboottime ();

    diff = boot + stamp;
    printf ("%s: %s", argv[1], ctime (&diff));

    return EXIT_SUCCESS;
}