From ca505e62fa1f42332691ad4c6c413f6b5082a449 Mon Sep 17 00:00:00 2001 From: axis6404 Date: Wed, 2 Jul 2025 00:50:54 +0900 Subject: [PATCH] Add RTC When ntpc is run as root, the RTC datetime is also set at the same time. This will ensure that the correct time is maintained by the RTC even after restart. Passing through the If you do not have access to /dev/rtc0, only the RTC setting will be skipped. --- ntpc.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ntpc.c b/ntpc.c index c5caf28..d58fad8 100644 --- a/ntpc.c +++ b/ntpc.c @@ -11,6 +11,10 @@ #include #include #include +#include +#include +#include +#include #define I_MISC 0 #define I_ORTIME 6 @@ -25,6 +29,9 @@ #endif +void syncToRTC(); + + // 0 = ok, 1 = failed, 2 = permanent failure static int ntpc(struct in_addr addr) { @@ -127,6 +134,8 @@ static int ntpc(struct in_addr addr) strftime(s, sizeof(s), "%a, %d %b %Y %H:%M:%S %z", localtime(&tv.tv_sec)); sprintf(q, "Time Updated: %s [%s%lds]", s, diff > 0 ? "+" : "", diff); + + syncToRTC(); } else { t = time(0); @@ -146,6 +155,39 @@ static int ntpc(struct in_addr addr) } +void syncToRTC() +{ + int fd = 0; + struct timeval tv; + struct tm localtm; + //struct rtc_time rtctm; + char s[64]; + + gettimeofday(&tv, NULL); + localtime_r(&tv.tv_sec, &localtm); + + strftime(s, sizeof(s), "%a, %d %b %Y %H:%M:%S %z", &localtm); + printf("syncToRTC(): %s\n", s); + + fd = open("/dev/rtc0", O_RDONLY); + if (fd == -1) + { + printf("ERROR: can't open /dev/rtc0 ...\n"); + return; + } + + int ret = ioctl(fd, RTC_SET_TIME, &localtm); + if(ret == -1) + { + close(fd); + printf("ERROR: can't set RTC...: %s\n", strerror(errno)); + return; + } + + close(fd); + return; +} + // -----------------------------------------------------------------------------