buildroot 构建根文件系统(8)添加网络时间同步

发布时间 2023-09-13 14:46:50作者: 掌控命运

一、开发背景

  构建最小系统后成功运行后,时间都是从初始化时间开始计算,形如:Thu Jan  1 09:57:55 UTC 1970

二、开发需求

  开机联网后自动从网络中获取最新的时间,同步到系统中

三、开发环境

  Linux Ubuntu 4.15.0-65-generic + buildroot-2023.02.3 + i.mx6d(cortex-A9)

四、实现步骤

  1、配置时钟分区,即 Install timezone info

    地球上不同的地点会存在时差,需要指定时区,如下

    > System configuration

      > Install timezone info 

  2、配置 ntp ,即网络时钟协议

    板卡作为客户端,通过网络时钟协议向服务器获取时钟时间,主要 ntpd 和 ntpdate

    ntpd 是缓慢同步,ntpdate 是立刻同步,参考链接:https://blog.csdn.net/m0_46222499/article/details/124145544

    > Target packages

      > Networking applications

        > ntp  

        > ntpd

        > ntpdate  

  3、buildroot 配置运行

  4、配置时钟分区和启动时钟更新

    1)选择时区覆盖到本地时间,下面选择的是香港时间

      cp /usr/share/zoneinfo/Asia/Hong_Kong /etc/localtime

    2) 关闭网络时间同步进程,否则会导致 ntpdate 失败

      /etc/init.d/S49ntp stop

    3)从腾讯云连接网络时间同步到板卡
      ntpdate 139.199.215.251

    4)启动网络时间同步进程

      /etc/init.d/S49ntp start 

    5)修改 /etc/ntp.conf,指定同步时间的服务器

#server 0.pool.ntp.org iburst
#server 1.pool.ntp.org iburst
#server 2.pool.ntp.org iburst
#server 3.pool.ntp.org iburst

# prefer 表示优先选择 
# ntp.ntsc.ac.cn(114.118.7.161) 为中国科学院ntp授时服务器
# time1.cloud.tencent.com(139.199.215.251) 腾讯云ntp授时服务器
server ntp.ntsc.ac.cn
server time1.cloud.tencent.com prefer

# Allow only time queries, at a limited rate, sending KoD when in excess.
# Allow all local queries (IPv4, IPv6)
restrict default nomodify nopeer noquery limited kod
restrict 127.0.0.1
restrict [::1]

     6)查看时间:OK