嵌入式linux C语言 如何同步系统时钟到硬件时钟

本文解释了使用settimeofday设置系统时间的方法及其局限性,并介绍了如何通过hwclock来同步硬件时间,确保系统重启后时间设置正确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用settimeofday设置时间后, 重启系统时间并没有设置成功是因为settimeofday,紧紧能设置系统时间并不能设置硬件时间,

开机时linux会从硬件的rtc的时钟芯片中获取一次硬件时间,然后以此为基础来运行系统时间。
settimeofday  相当于date shell命令,紧紧能设置系统时间。

如果想设置硬件时间,需要一个hwclock -w shell原理的函数来写硬件的rtc。

扒一扒 busybox的  hwclock.c源码(http://www.codeforge.cn/read/97203/hwclock.c__html)

可以知道这么抄写功能源码:

static void write_rtc(time_t t, int utc)                                                                                                                  
{
	int rtc;
	struct tm tm;

	if (( rtc = open ( "/dev/rtc", O_WRONLY )) < 0 )
	{
		if (( rtc = open ( "/dev/misc/rtc", O_WRONLY )) < 0 )
		bb_perror_msg_and_die ( "Could not access RTC" );
	}
	tm = *( utc ? gmtime ( &t ) : localtime ( &t ));
	tm. tm_isdst = 0;

	if ( ioctl ( rtc, RTC_SET_TIME, &tm ) < 0 )
	bb_perror_msg_and_die ( "Could not set the RTC time" );

	close ( rtc );
}




也可执行system系统调用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值