实现嵌入式linux自动同步网络时间---NTP

版权声明:凡本人原创,转发请注明出处,谢谢! https://blog.csdn.net/qq_41248872/article/details/83622146

因为ARM板断电重启问题,为保证能获取到准确的实时时间,所以需要实现自动从网络上获取时间,这就需要用到NTP。NTP是网络时间协议(Network Time Protocol)的简称,它是用来同步网络中各个计算机设备的时间的协议。目前有第三方的代码可以支持NTP,本文讲诉ntpclient的用法。

ntpclient is an NTP (RFC-1305) client for unix-alike computers. Its functionality is a small subset of xntpd, but IMHO performs better (or at least has the potential to function better) within that limited scope. Since it is much smaller than xntpd, it is also more relevant for embedded computers.
ntpclient is Copyright (C) 1997-2015 Larry Doolittle, and may be freely copied and modified according to the terms of the GNU General Public License, version 2.

ntpclient的下载地址是:http://doolittle.icarus.com/ntpclient/

下载好后,解压,进入解压后的目录进行交叉编译

1.修改Makefile

# To cross-compile
    CC = arm-none-linux-gnueabi-gcc

2.交叉编译

make

3.拷贝编译得到的ntpclient文件至目标板/sbin/目录下,并加可执行权限chmod  +x   ntpclient

然后我们需要一个网络授时服务器网址

http://www.ntp.org.cn/

这个是授时中心网页,在这个上面可以找到需要的授时中心网址

然后我们在开发板上运行程序

 ntpclient -s -d -c 1 -i 5 -h 202.108.6.95

设备会返回如下

[root@iTOP-4412]# ntpclient -s -d -c 1 -i 5 -h 202.108.6.95
Configuration:
  -c probe_count 1
  -d (debug)     1
  -g goodness    0
  -h hostname    202.108.6.95
  -i interval    5
  -l live        0
  -p local_port  0
  -q min_delay   800.000000
  -s set_clock   1
  -x cross_check 1
Listening...
Sending ...
packet of length 48 received
Source: INET Port 123 host 202.108.6.95
LI=0  VN=3  Mode=4  Stratum=2  Poll=4  Precision=-23
Delay=961.3  Dispersion=40679.9  Refid=10.69.2.34
Reference 3750052005.779027
(sent)    3590806877.094690
Originate 3590806877.094690
Receive   3750052666.964639
Transmit  3750052666.964667
Our recv  3590806877.137947
Total elapsed:  43425.00
Server stall:      27.02
Slop:           43397.98
Skew:          159245789848483.56
Frequency:             0
 day   second     elapsed    stall     skew  dispersion  freq
set time to 1541063866.964667000
41560 22877.138   43425.0     27.0  159245789848483.6  40679.9         0

其中那些参数可以阅读解压后的目录下的README文件,里面有详细的说明,需要提示的是-g不能使用,可能是嵌入式设备不支持。

使用date来查看一下系统时间:

Thu Nov  1 17:44:25 CST 2018

如果时区不是中国的东八区,可设置环境变量

export TZ=CST-8
设置后就可以显示中国时间了。

接下来是将前面命令加入开发板启动脚本,从而实现上电自动同步网络时间。

1.在开机脚本(我的是/etc/init.d/rcS)中修改下面几句话:

       #date -s "2018-10-31 11:20:35"     (注释掉这一行)

       ntpclient -s -d -c 1 -i 5 -h 202.108.6.95 >/dev/null &   (加入这一行,需加在获取网络命令行之后,确保先有网)

2.然后是添加系统环境变量,让开机后自动使用东八区(若之前已修改过系统硬件时钟配置文件,已改为东八区,则无需此步操作)

开发板文件系统/etc/profile中添加

export TZ=CST-8

然后就可以当开发板上电自动同步时间了。

猜你喜欢

转载自blog.csdn.net/qq_41248872/article/details/83622146