/*
 * برنامه خطای منطقی دارد. امکان تغییر تاریخ و ساعت سیستم به زمانی
 * کمتر از CLOCK_MONOTONIC وجود ندارد.
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <err.h>

void printGMTLocalTime(time_t *t);

int
main(void)
{
    struct timeval tv;
    struct timespec ts;
    time_t t;

    if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
        err(EXIT_FAILURE, "clock_gettime");

    printf("CLOCK_MONOTONIC time: ");
    printf("sec=%ld nsec=%ld\n", ts.tv_sec, ts.tv_nsec);

    tv.tv_usec = 0;
    //-----------------------------------------------------
    tv.tv_sec = ts.tv_sec - 10;     // خطا اینجاست
    printf("settimeofday() with tv_sec=%ld\n", tv.tv_sec);
    if (settimeofday(&tv, NULL) == -1)
        perror(NULL);
    else {
        t = time(NULL);
        printGMTLocalTime(&t);
    }

    //-----------------------------------------------------
    tv.tv_sec = ts.tv_sec + 10;
    printf("settimeofday() with tv_sec=%ld\n", tv.tv_sec);
    if (settimeofday(&tv, NULL) == -1)
        perror(NULL);
    else {
        t = time(NULL);
        printGMTLocalTime(&t);
    }


    exit(EXIT_SUCCESS);
}

void
printGMTLocalTime(time_t *t)
{
    struct tm *tm;

    if ( (tm = gmtime(t)) == NULL)
        err(EXIT_FAILURE, "gmtime");
    printf("GMT time:   %s", asctime(tm));
    printf("local time: %s", ctime(t));
}
