linux c 系统时间设置与获取
获取时间
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
int GetSystemTime(char* out)
{
struct timeval t;
time_t b_time;
struct tm *tim;
b_time = time(NULL);
tim = localtime(&b_time);
gettimeofday(&t, NULL);
return sprintf(out, "%d-%d-%d,%d:%d:%d:%d",
tim->tm_year + 1900, tim->tm_mon + 1, tim->tm_mday, tim->tm_hour,
tim->tm_min, tim->tm_sec, t.tv_usec / 1000);
}
设置时间
网上大部分都是陈旧的方法,在我的内核(linux 5.4)中默认没启用 settimeofday()函数.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
旧的方法
void SetSysTime(void)
{
struct tm tim = {
.tm_year = 2021 - 1900,
.tm_mon = 3 - 1,
.tm_mday = 10,
.tm_hour = 18,
.tm_min = 17,
.tm_sec = 5,
};
struct timeval tv_set;
tv_set.tv_sec = mktime(&tim );
tv_set.tv_usec = 0;
if (settimeofday(&tv_set,NULL)<0) {
perror("settimeofday");
}
}
新的方法
void SetSysTime(void)
{
struct tm tim = {
.tm_year = 2021 - 1900,
.tm_mon = 3 - 1,
.tm_mday = 10,
.tm_hour = 18,
.tm_min = 17,
.tm_sec = 5,
};
struct timespec tv_set;
tv_set.tv_sec = mktime(&tim );
tv_set.tv_nsec = 0;
if (clock_settime(CLOCK_REALTIME, &tv_set)<0) {
perror("clock_settime");
}
}
关于 CLOCK_REALTIME
查看linux man page.