注意:没有必要直接操作/dev/rtc0这个节点

:要用应用层的角度看待问题

rtc.h

/*
 * rtc.h — 实时时钟接口
 *
 * 读取 / 设置系统时间。底层走标准 C 库 time() / settimeofday(),
 * 设置时间后自动调用 hwclock -w 同步到硬件 RTC。
 * 不直接操作 /dev/rtc0 节点。
 */

#ifndef RTC_H
#define RTC_H

#include <time.h>

int  rtc_get_time(struct tm *t);
int  rtc_set_time(const struct tm *t);

#endif

rtc.c

#include "rtc.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rtc_get_time(struct tm *t)
{
    time_t now = time(NULL);
    if (now == (time_t)-1) {
        perror("time");
        return -1;
    }
    if (localtime_r(&now, t) == NULL) {
        perror("localtime_r");
        return -1;
    }
    return 0;
}

int rtc_set_time(const struct tm *t)
{
    char cmd[128];
    snprintf(cmd, sizeof(cmd),
             "date -s '%04d-%02d-%02d %02d:%02d:%02d' 2>/dev/null",
             t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
             t->tm_hour, t->tm_min, t->tm_sec);

    if (system(cmd) != 0) {
        fprintf(stderr, "date -s failed\n");
        return -1;
    }

    if (system("hwclock -w 2>/dev/null") != 0) {
        /* hwclock 写入硬件 RTC 失败,不影响系统时间 */
    }
    return 0;
}