clock_settime不适用于CLOCK_REALTIME

时间:2019-11-04 11:26:05

标签: c linux time

我编写了一个示例代码来使用clock_settime设置时间。

#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char argv[])
{
    struct timespec walltime;

    clock_gettime(CLOCK_REALTIME, &walltime);
    perror("clock_gettime");
    printf("Current wall time:%s\n", ctime(&walltime.tv_sec));

    walltime.tv_sec += 10*60;
    printf("Setting wall time to :%s\n", ctime(&walltime.tv_sec));
    clock_settime(CLOCK_REALTIME, &walltime);
    perror("clock_settime");

    clock_gettime(CLOCK_REALTIME, &walltime);
    perror("clock_gettime");
    printf("Current wall time:%s\n", ctime(&walltime.tv_sec));
    return 0;
}

程序输出:

clock_gettime: Success
Current wall time:Mon Nov  4 03:24:43 2019

Setting wall time to :Mon Nov  4 03:34:43 2019

clock_settime: Success
clock_gettime: Success
Current wall time:Mon Nov  4 03:34:43 2019

看起来正确,但是当我第二次运行它时,新时间不会更新。

clock_gettime: Success
Current wall time:Mon Nov  4 03:25:12 2019

Setting wall time to :Mon Nov  4 03:35:12 2019

clock_settime: Success
clock_gettime: Success
Current wall time:Mon Nov  4 03:35:12 2019

Date命令还会显示旧值。

$ date
Mon Nov  4 03:25:30 PST 2019

此行为正确吗

0 个答案:

没有答案