简体   繁体   English

使用C库功能设置系统时间

[英]system time setting using c library function

我可以使用struct tm和time(),localtime(),asctime()来获取系统时间。但是我需要有关如何使用c程序设置系统时间的帮助。

if you don't want to execute a shell command you can (as you mentioned) use the settimeofday, i would start by reading the MAN page , or looking for some examples 如果您不想执行shell命令,则可以(如您所述)使用settimeofday,我将从阅读MAN页开始 ,或者寻找一些示例

here's an example: 这是一个例子:

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

int main(int argc, char *argv[])
{
    struct timeval now;
    int rc;

    now.tv_sec=866208142;
    now.tv_usec=290944;

    rc=settimeofday(&now, NULL);
    if(rc==0) {
        printf("settimeofday() successful.\n");
    }
    else {
        printf("settimeofday() failed, "
        "errno = %d\n",errno);
        return -1;
    }

    return 0;
}

Shamelessly ripped From IBMs documentation , the struct timeval struct holds the number of seconds (as a long ) plus the number of microseconds (as a long ) from 1 January 1970, 00:00:00 UTC (Unix Epoch time). IBM文档中毫不客气地窃取 struct timeval struct保留从1970年1月1日UTC(Unix Epoch时间)开始的秒数(以long )加上微秒数(以long )。 So you will need to calculate these numbers in order to set the time. 因此,您将需要计算这些数字以设置时间。 you can use these helper functions , to better handle dealing with the timeval struct. 您可以使用这些帮助器函数来更好地处理timeval结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM