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 硬件交互时,可能需要额外处理世纪信息。
相关推荐
saynaihe31 分钟前
2025吐槽季第一弹---腾讯云EO边缘安全加速平台服务
运维·安全·云计算·腾讯云
@#---39 分钟前
删除驱动精灵的详细过程
运维·服务器
likeyou~coucou1 小时前
自动化之ansible(二)
运维·自动化·ansible
小红帽2.01 小时前
客服系统自动化方案:揭秘全渠道智能服务解决方案 vx: haotsh
运维·自动化
reset20211 小时前
ubuntu离线安装ollama
linux·ubuntu·ollama
放氮气的蜗牛2 小时前
Linux命令终极指南:从入门到精通掌握150+核心指令
linux·运维·服务器
网络安全King2 小时前
devops 工具 网络安全
运维·web安全·devops
梁萌2 小时前
04-DevOps-安装并初始化Jenkins
运维·jenkins·devops
DC_BLOG2 小时前
Linux-Ansible模块进阶
linux·运维·服务器·ansible
Imagine Miracle2 小时前
【Deepseek】Linux 本地部署 Deepseek
linux·运维·服务器