hwclock(Linux)

http://www.cnblogs.com/diyunpeng/archive/2009/11/23/1608816.html

hwclock(Linux)

  在Linux中有硬件时钟与系统时钟两种时钟。硬件时钟是指主机板上的时钟设备,也就是通常可在BIOS画面设定的时钟。系统时钟则是指kernel中的 时钟。当Linux启动时,系统时钟会去读取硬件时钟的设定,之後系统时钟即独立运作。所有Linux相关指令与函数都是读取系统时钟的设定。 hwclock实现了BIOS和linux的时间同步

 

既然Linux有两个时钟系统,那么大家所使用的Linux默认使用哪种时钟系统呢?会不回出现两种系统时钟冲突的情况呢?这些疑问和担心不无道理。首先,Linux并没有默认哪个时钟系统。当Linux启动时,硬件时钟会去读取系统时钟的设置,然后系统时钟就会独立于硬件运作

从Linux启动过程来看,系统时钟和硬件时钟不会发生冲突,但Linux中的所有命令(包括函数)都是采用的系统时钟设置。不仅如此,系统时钟和硬件时钟还可以采用异步方式,即系统时间和硬件时间可以不同。这样做的好处对于普通用户意义不大,但对于Linux网络管理员却有很大的用处。例如,要将一个很大的网络中(跨越若干时区)的服务器同步,假如位于美国纽约的Linux服务器和北京的Linux服务器,其中一台服务器无须改变硬件时钟而只需临时设置一个系统时间,如要将北京服务器上的时间设置为纽约时间,两台服务器完成文件的同步后,再与原来的时钟同步一下即可。这样系统和硬件时钟就提供了更为灵活的操作。

在Linux中,用于时钟查看和设置的命令主要有date、hwclock和clock。其中,clock和hwclock用法相近,只不过clock命 令除了支持x86硬件体系外,还支持Alpha硬件体系。由于目前绝大多数用户使用x86硬件体系,所以可以视这两个命令为一个命令来学习

语法格式:

hwclock [--adjust][--debug][--hctosys][--show][--systohc][--test]
[--utc][--version][--set --date=<日期与时间>]

参数说明:

  • –adjust or -a

hwclock每次更改硬件时钟时,都会记录在/etc/adjtime文件中。使用adjust参数,可使hwclock根据先前的记录来估算硬件时钟的偏差,并用来校正目前的硬件时钟。

  • –hctosys or -s

将系统时钟调整为与目前的硬件时钟一致。

  • –set –date=<日期与时间>

设定硬件时钟。

  • –show or -r

显示硬件时钟的时间与日期。

  • –systohc or -w

将硬件时钟调整为与目前的系统时钟一致。

  • –version or -v

显示版本信息。

  • –debug

显示hwclock执行时详细的信息。

  • –test

仅测试程序,而不会实际更改硬件时钟。

  • –utc

若要使用格林威治时间,请加入此参数,hwclock会执行转换的工作。

同步系统时钟和硬件时钟

# hwclock –w

设置硬件时钟时间:

# hwclock --set --date="9/8/2007 16:45:05"

查看硬件时钟

# hwclock -r

1.在虚拟终端中使用date命令来查看和设置系统时间
    查看系统时钟的操作:
    # date

    设置系统时钟的操作:
    # date 091713272003.30

    通用的设置格式:
    # date 月日时分年.秒

    2.使用hwclock或clock命令查看和设置硬件时钟
    查看硬件时钟的操作:
    # hwclock --show 或
    # clock --show
    2003年09月17日 星期三 13时24分11秒 -0.482735 seconds

    设置硬件时钟的操作:
    # hwclock --set --date="09/17/2003 13:26:00"

    或者
    # clock --set --date="09/17/2003 13:26:00"

    通用的设置格式:hwclock/clock --set --date=“月/日/年时:分:秒”。

    3.同步系统时钟和硬件时钟

    Linux系统(笔者使用的是Red Hat 8.0,其它系统没有做过实验)默认重启后,硬件时钟和系统时钟同步。如果不大方便重新启动的话(服务器通常很少重启),使用clock或hwclock命令来同步系统时钟和硬件时钟。

    硬件时钟与系统时钟同步:
    # hwclock --hctosys

    或者
    # clock --hctosys

    上面命令中,--hctosys表示Hardware Clock to SYStem clock。

    系统时钟和硬件时钟同步:
    # hwclock --systohc

    或者
    # clock --systohc

 


http://linux.die.net/man/8/hwclock

 

hwclock(8) - Linux man page

Name

hwclock - query and set the hardware clock (RTC)

Synopsis

hwclock -r or hwclock --show
hwclock -w or hwclock --systohc
hwclock -s or hwclock --hctosys
hwclock -a or hwclock --adjust
hwclock -v or hwclock --version
hwclock --set --date=newdate
hwclock --getepoch
hwclock --setepoch --epoch=year

other options:

[-u|--utc] --localtime --noadjfile --directisa --test [-D|--debug]

and arcane options for DEC Alpha:

[-A|--arc] [-J|--jensen] [-S|--srm] [-F|--funky-toy]

Minimum unique abbreviations of all options are acceptable.

Also, -h asks for a help message.

Description

hwclock is a tool for accessing the Hardware Clock. You can display the current time,set the Hardware Clock to a specified time, set the Hardware Clock to the System Time, and set the System Time from the Hardware Clock.

You can also run hwclock periodically to insert or remove time from the Hardware Clock to compensate for systematic drift (where the clockconsistently gains or loses time at a certain rate if left to run).

Options

You need exactly one of the following options to tell hwclock what function to perform:

--show
Read the Hardware Clock and print the time on Standard Output. The time shown is always in local time, even if you keep your Hardware Clock in CoordinatedUniversal Time. See the --utc option.
--set
Set the Hardware Clock to the time given by the --date option.
--hctosys
Set the System Time from the Hardware Clock.

Also set the kernel's timezone value to the local timezone as indicated by the TZ environment variable and/or /usr/share/zoneinfo, astzset(3) would interpret them. The obsolete tz_dsttime field of the kernel's timezone value is set to DST_NONE. (For details on what this fieldused to mean, see settimeofday(2).)

This is a good option to use in one of the system startup scripts.

--systohc
Set the Hardware Clock to the current System Time.
--adjust
Add or subtract time from the Hardware Clock to account for systematic drift since the last time the clock was set or adjusted. See discussion below.
--getepoch
Print the kernel's Hardware Clock epoch value to standard output. This is the number of years into AD to which a zero year value in the Hardware Clockrefers. For example, if you are using the convention that the year counter in your Hardware Clock contains the number of full years since 1952, then thekernel's Hardware Counter epoch value must be 1952.

This epoch value is used whenever hwclock reads or sets the Hardware Clock.

--setepoch
Set the kernel's Hardware Clock epoch value to the value specified by the --epoch option. See the --getepoch option for details.
--version
Print the version of hwclock on Standard Output.
--date=date_string
You need this option if you specify the --set option. Otherwise, it is ignored. This specifies the time to which to set the Hardware Clock. Thevalue of this option is an argument to the date(1) program. For example,

hwclock --set --date="9/22/96 16:45:05"

The argument is in local time, even if you keep your Hardware Clock in Coordinated Universal time. See the --utc option.

--epoch=year
Specifies the year which is the beginning of the Hardware Clock's epoch. I.e. the number of years into AD to which a zero value in the Hardware Clock'syear counter refers. It is used together with the --setepoch option to set the kernel's idea of the epoch of the Hardware Clock, or otherwise to specify theepoch for use with direct ISA access.

For example, on a Digital Unix machine:

hwclock --setepoch --epoch=1952

The following options apply to most functions.

--utc --localtime
Indicates that the Hardware Clock is kept in Coordinated Universal Time or local time, respectively. It is your choice whether to keep your clock in UTC orlocal time, but nothing in the clock tells which you've chosen. So this option is how you give that information to hwclock.

If you specify the wrong one of these options (or specify neither and take a wrong default), both setting and querying of the Hardware Clock will be messedup.

If you specify neither --utc nor --localtime , the default is whichever was specified the last time hwclock was used to set the clock(i.e. hwclock was successfully run with the --set , --systohc , or --adjust options), as recorded in the adjtime file. If the adjtime filedoesn't exist, the default is local time.

--noadjfile
disables the facilities provided by /etc/adjtime. hwclock will not read nor write to that file with this option. Either --utc or --localtime must be specified when using this option.
--directisa
is meaningful only on an ISA machine or an Alpha (which implements enough of ISA to be, roughly speaking, an ISA machine for hwclock's purposes).For other machines, it has no effect. This option tells hwclock to use explicit I/O instructions to access the Hardware Clock. Without this option, hwclock will try to use the /dev/rtc device (which it assumes to be driven by the rtc device driver). If it is unable to open the device (for read), itwill use the explicit I/O instructions anyway.

The rtc device driver was new in Linux Release 2.

--badyear
Indicates that the Hardware Clock is incapable of storing years outside the range 1994-1999. There is a problem in some BIOSes (almost all Award BIOSesmade between 4/26/94 and 5/31/95) wherein they are unable to deal with years after 1999. If one attempts to set the year-of-century value to something lessthan 94 (or 95 in some cases), the value that actually gets set is 94 (or 95). Thus, if you have one of these machines, hwclock cannot set the yearafter 1999 and cannot use the value of the clock as the true time in the normal way.

To compensate for this (without your getting a BIOS update, which would definitely be preferable), always use --badyear if you have one of thesemachines. When hwclock knows it's working with a brain-damaged clock, it ignores the year part of the Hardware Clock value and instead tries to guessthe year based on the last calibrated date in the adjtime file, by assuming that that date is within the past year. For this to work, you had better do ahwclock --set or hwclock --systohc at least once a year!

Though hwclock ignores the year value when it reads the Hardware Clock, it sets the year value when it sets the clock. It sets it to 1995, 1996,1997, or 1998, whichever one has the same position in the leap year cycle as the true year. That way, the Hardware Clock inserts leap days where they belong.Again, if you let the Hardware Clock run for more than a year without setting it, this scheme could be defeated and you could end up losing a day.

hwclock warns you that you probably need --badyear whenever it finds your Hardware Clock set to 1994 or 1995.

--srm
This option is equivalent to --epoch=1900 and is used to specify the most common epoch on Alphas with SRM console.
--arc
This option is equivalent to --epoch=1980 and is used to specify the most common epoch on Alphas with ARC console (but Ruffians have epoch 1900).
--jensen --funky-toy
These two options specify what kind of Alpha machine you have. They are invalid if you don't have an Alpha and are usually unnecessary if you do, because hwclock should be able to determine by itself what it's running on, at least when /proc is mounted. (If you find you need one of these options tomake hwclock work, contact the maintainer to see if the program can be improved to detect your system automatically. Output of 'hwclock --debug' and'cat /proc/cpuinfo' may be of interest.)

--jensen means you are running on a Jensen model.

--funky-toy means that on your machine, one has to use the UF bit instead of the UIP bit in the Hardware Clock to detect a time transition. "Toy" inthe option name refers to the Time Of Year facility of the machine.

--test
Do everything except actually updating the Hardware Clock or anything else. This is useful, especially in conjunction with --debug, in learningabout hwclock.
--debug
Display a lot of information about what hwclock is doing internally. Some of its function is complex and this output can help you understand how theprogram works.

Notes

Clocks in a Linux System

There are two main clocks in a Linux system:

The Hardware Clock: This is a clock that runs independently of any control program running in the CPU and even when the machine is powered off.

On an ISA system, this clock is specified as part of the ISA standard. The control program can read or set this clock to a whole second, but the controlprogram can also detect the edges of the 1 second clock ticks, so the clock actually has virtually infinite precision.

This clock is commonly called the hardware clock, the real time clock, the RTC, the BIOS clock, and the CMOS clock. Hardware Clock, in its capitalized form,was coined for use by hwclock because all of the other names are inappropriate to the point of being misleading.

The System Time: This is the time kept by a clock inside the Linux kernel and driven by a timer interrupt. (On an ISA machine, the timer interrupt ispart of the ISA standard). It has meaning only while Linux is running on the machine. The System Time is the number of seconds since 00:00:00 January 1, 1970UTC (or more succinctly, the number of seconds since 1969). The System Time is not an integer, though. It has virtually infinite precision.

The System Time is the time that matters. The Hardware Clock's basic purpose in a Linux system is to keep time when Linux is not running. You initialize theSystem Time to the time from the Hardware Clock when Linux starts up, and then never use the Hardware Clock again. Note that in DOS, for which ISA wasdesigned, the Hardware Clock is the only real time clock.

It is important that the System Time not have any discontinuities such as would happen if you used the date(1L) program to set it while thesystem is running. You can, however, do whatever you want to the Hardware Clock while the system is running, and the next time Linux starts up, it will do sowith the adjusted time from the Hardware Clock. You can also use the program adjtimex(8) to smoothly adjust the System Time while the systemruns.

A Linux kernel maintains a concept of a local timezone for the system. But don't be misled -- almost nobody cares what timezone the kernel thinks it is in.Instead, programs that care about the timezone (perhaps because they want to display a local time for you) almost always use a more traditional method ofdetermining the timezone: They use the TZ environment variable and/or the /usr/share/zoneinfo directory, as explained in the man page fortzset(3). However, some programs and fringe parts of the Linux kernel such as filesystems use the kernel timezone value. An example is the vfatfilesystem. If the kernel timezone value is wrong, the vfat filesystem will report and set the wrong timestamps on files.

hwclock sets the kernel timezone to the value indicated by TZ and/or /usr/share/zoneinfo when you set the System Time using the--hctosys option.

The timezone value actually consists of two parts: 1) a field tz_minuteswest indicating how many minutes local time (not adjusted for DST) lags behind UTC,and 2) a field tz_dsttime indicating the type of Daylight Savings Time (DST) convention that is in effect in the locality at the present time. This secondfield is not used under Linux and is always zero. (See also settimeofday(2).)

How hwclock Accesses the Hardware Clock

hwclock Uses many different ways to get and set Hardware Clock values. The most normal way is to do I/O to the device special file /dev/rtc, which ispresumed to be driven by the rtc device driver. However, this method is not always available. For one thing, the rtc driver is a relatively recent addition toLinux. Older systems don't have it. Also, though there are versions of the rtc driver that work on DEC Alphas, there appear to be plenty of Alphas on which thertc driver does not work (a common symptom is hwclock hanging).

On older systems, the method of accessing the Hardware Clock depends on the system hardware.

On an ISA system, hwclock can directly access the "CMOS memory" registers that constitute the clock, by doing I/O to Ports 0x70 and 0x71. It doesthis with actual I/O instructions and consequently can only do it if running with superuser effective userid. (In the case of a Jensen Alpha, there is no wayfor hwclock to execute those I/O instructions, and so it uses instead the /dev/port device special file, which provides almost as low-level an interfaceto the I/O subsystem).

This is a really poor method of accessing the clock, for all the reasons that user space programs are generally not supposed to do direct I/O and disableinterrupts. Hwclock provides it because it is the only method available on ISA and Alpha systems which don't have working rtc device drivers available.

On an m68k system, hwclock can access the clock via the console driver, via the device special file /dev/tty1.

hwclock tries to use /dev/rtc. If it is compiled for a kernel that doesn't have that function or it is unable to open /dev/rtc, hwclock willfall back to another method, if available. On an ISA or Alpha machine, you can force hwclock to use the direct manipulation of the CMOS registerswithout even trying /dev/rtc by specifying the --directisa option.

The Adjust Function

The Hardware Clock is usually not very accurate. However, much of its inaccuracy is completely predictable - it gains or loses the same amount of time everyday. This is called systematic drift. hwclock's "adjust" function lets you make systematic corrections to correct the systematic drift.

It works like this: hwclock keeps a file, /etc/adjtime, that keeps some historical information. This is called the adjtime file.

Suppose you start with no adjtime file. You issue a hwclock --set command to set the Hardware Clock to the true current time. Hwclock createsthe adjtime file and records in it the current time as the last time the clock was calibrated. 5 days later, the clock has gained 10 seconds, so you issueanother hwclock --set command to set it back 10 seconds. Hwclock updates the adjtime file to show the current time as the last time the clock wascalibrated, and records 2 seconds per day as the systematic drift rate. 24 hours go by, and then you issue a hwclock --adjust command. Hwclockconsults the adjtime file and sees that the clock gains 2 seconds per day when left alone and that it has been left alone for exactly one day. So it subtracts2 seconds from the Hardware Clock. It then records the current time as the last time the clock was adjusted. Another 24 hours goes by and you issue anotherhwclock --adjust. Hwclock does the same thing: subtracts 2 seconds and updates the adjtime file with the current time as the last time the clockwas adjusted.

Every time you calibrate (set) the clock (using --set or --systohc ), hwclock recalculates the systematic drift rate based on how longit has been since the last calibration, how long it has been since the last adjustment, what drift rate was assumed in any intervening adjustments, and theamount by which the clock is presently off.

A small amount of error creeps in any time hwclock sets the clock, so it refrains from making an adjustment that would be less than 1 second. Lateron, when you request an adjustment again, the accumulated drift will be more than a second and hwclock will do the adjustment then.

It is good to do a hwclock --adjust just before the hwclock --hctosys at system startup time, and maybe periodically while the system isrunning via cron.

The adjtime file, while named for its historical purpose of controlling adjustments only, actually contains other information for use by hwclock inremembering information from one invocation to the next.

The format of the adjtime file is, in ASCII:

Line 1: 3 numbers, separated by blanks: 1) systematic drift rate in seconds per day, floating point decimal; 2) Resulting number of seconds since 1969 UTCof most recent adjustment or calibration, decimal integer; 3) zero (for compatibility with clock(8)) as a decimal integer.

Line 2: 1 number: Resulting number of seconds since 1969 UTC of most recent calibration. Zero if there has been no calibration yet or it is known that anyprevious calibration is moot (for example, because the Hardware Clock has been found, since that calibration, not to contain a valid time). This is a decimalinteger.

Line 3: "UTC" or "LOCAL". Tells whether the Hardware Clock is set to Coordinated Universal Time or local time. You can always override this value withoptions on the hwclock command line.

You can use an adjtime file that was previously used with the clock(8) program with hwclock.

Automatic Hardware Clock Synchronization By the Kernel

You should be aware of another way that the Hardware Clock is kept synchronized in some systems. The Linux kernel has a mode wherein it copies the SystemTime to the Hardware Clock every 11 minutes. This is a good mode to use when you are using something sophisticated like ntp to keep your System Timesynchronized. (ntp is a way to keep your System Time synchronized either to a time server somewhere on the network or to a radio clock hooked up to yoursystem. See RFC 1305).

This mode (we'll call it "11 minute mode") is off until something turns it on. The ntp daemon xntpd is one thing that turns it on. You can turn it off byrunning anything, including hwclock --hctosys, that sets the System Time the old fashioned way.

To see if it is on or off, use the command adjtimex --print and look at the value of "status". If the "64" bit of this number (expressed in binary)equal to 0, 11 minute mode is on. Otherwise, it is off.

If your system runs with 11 minute mode on, don't use hwclock --adjust or hwclock --hctosys. You'll just make a mess. It is acceptable to usea hwclock --hctosys at startup time to get a reasonable System Time until your system is able to set the System Time from the external source and start11 minute mode.

ISA Hardware Clock Century value

There is some sort of standard that defines CMOS memory Byte 50 on an ISA machine as an indicator of what century it is. hwclock does not use or setthat byte because there are some machines that don't define the byte that way, and it really isn't necessary anyway, since the year-of-century does a good jobof implying which century it is.

If you have a bona fide use for a CMOS century byte, contact the hwclock maintainer; an option may be appropriate.

Note that this section is only relevant when you are using the "direct ISA" method of accessing the Hardware Clock.

Environment Variables

TZ

Files

/etc/adjtime /usr/share/zoneinfo/ (/usr/lib/zoneinfo on old systems)/dev/rtc /dev/port /dev/tty1 /proc/cpuinfo

See Also

adjtimex(8), date(1), gettimeofday(2),settimeofday(2), crontab(1), tzset(3)

Authors

Written by Bryan Henderson, September 1996 (bryanh@giraffe-data.com), based on work done on theclock program by Charles Hedrick, Rob Hooft, and Harald Koenig. See the source code for complete history and credits.

Referenced By

rtc(4),rtcwake(8),time(7)

转载于:https://www.cnblogs.com/yuanfang/archive/2010/12/23/1914911.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值