【linux_C语言】手动设置系统时间和硬件时间||通过ntp同步更新系统时间

前言

在Linux中有硬件时钟与系统时钟等两种时钟。
当Linux系统启动时,系统时钟会去读硬件时钟,它们两是独立的,读完后,后面各自时间有可能不一样,可以进行同步,linux时间函数读的都是系统时钟

手动设置系统时钟并同步硬件时钟

先把年月日通过函数返回time_t 时间戳

//当前时区的墙钟时间转time_t 
time_t JTime_mktime_ex(unsigned int year, unsigned int month, unsigned int day, unsigned int hour, unsigned int minute, unsigned int second)
{
	struct tm stTm={0};
	stTm.tm_year = year - 1900;
	stTm.tm_mon = month - 1;
	stTm.tm_mday = day;
	stTm.tm_hour = hour;
	stTm.tm_min = minute;
	stTm.tm_sec = second;
    stTm.tm_isdst = -1;
	return mktime(&stTm);
}

通过stime函数设置系统时间并同步硬件时钟

time_t tm = JTime_mktime_ex(2022,6,12,21,0,0);
int ret = stime(&tm);
//配置时间时需要把系统时钟同步到硬件时钟.
system("hwclock -w -u");

通过ntp服务器更新系统时间(后续更新)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

I&You

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值