Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

c - How Do You Programmatically Set the Hardware Clock on Linux?

Linux provides the stime(2) call to set the system time. However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.

Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals. However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.

How do you ensure that the hardware clock gets updated when you set the system time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out the rtc man-page for details, but if you are logged in as root, something like this:

#include <linux/rtc.h>
#include <sys/ioctl.h>


    struct       rtc_time {
        int         tm_sec;      
        int         tm_min;      
        int         tm_hour;     
        int         tm_mday;     
        int         tm_mon;      
        int         tm_year;     
        int         tm_wday; /* unused */
        int         tm_yday; /* unused */
        int         tm_isdst;/* unused */
    };

int fd;
struct rtc_time rt;
/* set your values here */
fd = open("/dev/rtc", O_RDONLY);
ioctl(fd, RTC_SET_TIME, &rt);
close(fd);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...