CPU:RK3288
系統:Linux
IC:hym8563
在 Linux 系統中,指令 date 和 hwclock 都可以讀寫時間
date:讀寫系統時間,寫時間需要管理員權限
hwclock:讀寫硬件時間,也就是 rtc 模塊的時間,讀寫都必須有管理員權限
// 讀取當前系統時間 $ date Thu Oct 24 03:03:13 UTC 2019 // 普通用戶設置時間失敗 $ date 102411032019.00 date: cannot set date: Operation not permitted Thu Oct 24 11:03:00 UTC 2019 // 超級用戶設置時間成功,格式:月日時分年.秒 $ sudo date 102411032019.00 Thu Oct 24 11:03:00 UTC 2019 // 讀取當前系統時間,確認時間設置成功 // 小時與設置的11點不同,這是由於時區造成的 $ date Thu Oct 24 03:03:38 UTC 2019
設置時區的問題,請參考:[Linux] 通過指令修改時區 tzselect
$ date Thu Oct 24 14:22:50 CST 2019 // 查看硬件時間 $ sudo hwclock Thu 24 Oct 2019 02:22:54 PM CST .744709 seconds // 查看硬件時間 $ sudo hwclock -r Thu 24 Oct 2019 02:22:54 PM CST .744709 seconds // 查看硬件時間 $ sudo hwclock -show Thu 24 Oct 2019 02:22:54 PM CST .744709 seconds // 修改硬件時間,與系統時間相同 $ sudo hwclock -w // 修改系統時間,與硬件時間相同 $ sudo hwclock -w
rtc 測試 demo:
#include <stdio.h> #include <stdlib.h> #include <linux/rtc.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <time.h> int main(int argc, char *argv[]) { int fd, retval; struct rtc_time rtc_tm; time_t timep; struct tm *p; fd = open("/dev/rtc", O_RDONLY); if (fd == -1) { fprintf(stderr, "open /dev/rtc error\n"); exit(errno); } /* Read the RTC time/date */ retval = ioctl(fd, RTC_RD_TIME, &rtc_tm); if (retval == -1) { perror("ioctl"); exit(errno); } fprintf(stderr, "RTC date/time: %d/%d/%d %02d:%02d:%02d\n", rtc_tm.tm_mday, rtc_tm.tm_mon + 1, rtc_tm.tm_year + 1900, rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec); time(&timep); p = gmtime(&timep); fprintf(stderr, "OS date/time(UTC): %d/%d/%d %02d:%02d:%02d\n", p->tm_mday, p->tm_mon + 1, p->tm_year + 1900, p->tm_hour, p->tm_min, p->tm_sec); p = localtime(&timep); fprintf(stderr, "OS date/time(Local): %d/%d/%d %02d:%02d:%02d\n", p->tm_mday, p->tm_mon + 1, p->tm_year + 1900, p->tm_hour, p->tm_min, p->tm_sec); rtc_tm.tm_mday = 15; rtc_tm.tm_mon = 11; rtc_tm.tm_hour = 15; rtc_tm.tm_min = 15; retval = ioctl(fd, RTC_SET_TIME, &rtc_tm); if (retval == -1) { perror("ioctl"); exit(errno); } /* Write the RTC time/date */ retval = ioctl(fd, RTC_RD_TIME, &rtc_tm); if (retval == -1) { perror("ioctl"); exit(errno); } fprintf(stderr, "RTC date/time: %d/%d/%d %02d:%02d:%02d\n", rtc_tm.tm_mday, rtc_tm.tm_mon + 1, rtc_tm.tm_year + 1900, rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec); time(&timep); p = gmtime(&timep); fprintf(stderr, "OS date/time(UTC): %d/%d/%d %02d:%02d:%02d\n", p->tm_mday, p->tm_mon + 1, p->tm_year + 1900, p->tm_hour, p->tm_min, p->tm_sec); p = localtime(&timep); fprintf(stderr, "OS date/time(Local): %d/%d/%d %02d:%02d:%02d\n", p->tm_mday, p->tm_mon + 1, p->tm_year + 1900, p->tm_hour, p->tm_min, p->tm_sec); close(fd); return 0; }
參考:https://blog.csdn.net/u010703935/article/details/11728091
