Linux内核 -- RTC之`struct rtc_time` 字段解析

Linux Kernel 中 struct rtc_timetm_year 字段详解

1. struct rtc_time 的定义

在 Linux 内核中,struct rtc_time 用于表示实时时钟(RTC)时间。其定义如下:

c 复制代码
struct rtc_time {
    int tm_sec;   /* 分钟的秒数 (0-59) */
    int tm_min;   /* 小时的分钟数 (0-59) */
    int tm_hour;  /* 自午夜起的小时数 (0-23) */
    int tm_mday;  /* 月中的某一天 (1-31) */
    int tm_mon;   /* 自一月起的月数 (0-11) */
    int tm_year;  /* 自1900年以来的年份偏移值 */
    int tm_wday;  /* 自星期日起的天数 (0-6) */
    int tm_yday;  /* 自一月一日起的天数 (0-365) */
    int tm_isdst; /* 夏令时标志 */
};

2. tm_year 的含义

  • tm_year 表示年份的偏移值,其基准年份是 1900
  • 换句话说,
    • 如果 tm_year = 123,表示年份为 1900 + 123 = 2023
    • 如果 tm_year = 0,表示年份为 1900 + 0 = 1900

3. 使用中的注意事项

  • 获取时间时 :需要将 tm_year 加上 1900,转换为标准年份。
  • 设置时间时 :需要将标准年份减去 1900,然后赋值给 tm_year

4. 与用户空间的交互

  • 用户空间的标准库(如 glibc)中定义了类似的结构体 struct tm,其 tm_year 字段的含义与内核的 rtc_time 一致。
  • 因此,内核中的 struct rtc_time 和用户空间的 struct tm 可以直接转换。

5. 实际应用示例

获取时间

c 复制代码
struct rtc_time tm;
rtc_read_time(rtc, &tm);
int year = tm.tm_year + 1900; // 转换为标准年份
printk("Current year: %d\n", year);

设置时间

c 复制代码
struct rtc_time tm = {
    .tm_year = 2023 - 1900,  // 转换标准年份为 tm_year 的值
    .tm_mon = 11 - 1,        // 月份,从 0 开始
    .tm_mday = 30,
    .tm_hour = 12,
    .tm_min = 0,
    .tm_sec = 0,
};
rtc_set_time(rtc, &tm);

6. 与 RTC 硬件交互

  • 实时时钟硬件芯片(如 DS3231)可能以不同格式存储年份。例如,有些芯片仅存储两位数年份(如 00 表示 2000 年)。驱动程序需要将 RTC 硬件的年份格式转换为 tm_year 的格式。
  • 如果硬件仅支持 20 世纪和 21 世纪的年份,驱动程序通常会根据上下文决定世纪部分。

7. 常见问题

溢出问题

  • 由于 tm_year 是相对于 1900 的偏移值,其理论最大值取决于字段的类型(通常为 int)。
  • 在 32 位系统中,最大年份范围可达 INT_MAX - 1900

世纪问题

  • 某些硬件仅存储两位年份,转换时需要根据当前时间或用户设置推断世纪部分。

8. 小结

  • tm_year 是从 1900 开始的偏移值。
  • 获取和设置时间时需进行适当的加减操作以转换为标准年份。
  • 与 RTC 硬件交互时,可能需要额外处理世纪信息。
相关推荐
EMTime3 小时前
Docker运行OpenWRT
运维·docker·容器
lolo大魔王3 小时前
Linux 文件系统超全面详解(原理、结构、挂载、分区、inode、日志、管理命令)
linux·运维·服务器
磊 子4 小时前
详细讲解一下epoll
linux·io·epoll·io多路复用
printfLILEI5 小时前
php中的类与对象以及反序列化
linux·开发语言·php
zyl837215 小时前
Docker 使用手册
运维·docker·容器
古月方枘Fry6 小时前
MGRE实验
运维·服务器
叠叠乐6 小时前
redmi k90 pro max 强解BL,刷海外rom, 并刷入sukisu ultra
linux
stolentime6 小时前
FreeDomain 本地开发环境快速搭建指南
运维·服务器·网络
xiaoye-duck7 小时前
《Linux系统编程》Linux 进程间通信之管道基础解析:从匿名管道原理到基于管道的进程池实现
linux