Ioctl Interface

The the ioctl interface can be used to:
  • Obtain an RTC device handle
  • Configure RTC time
The following demo program provides an example of using the interface.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <linux/rtc.h>  /* Where the RTC ioctl commands is stored */
8 #include <errno.h>
9 #include <string.h>
10
11 #define RTC_DEVICE_NAME "/dev/rtc0"  /* The device name of the RTC device */
12
13 /* Set RTC time */
14 int set_rtc_time(int fd)
15 {
16  struct rtc_time rtc_tm;
17
18  rtc_tm.tm_year = 2022 - 1900; /* year, range: 101-199, which matches 2001-2099 */
19  rtc_tm.tm_mon = 7 - 1; /* month, range: 0-11, which matches 1-12 */
20  rtc_tm.tm_mday = 15; /* day */
21  rtc_tm.tm_hour = 14; /* hour */
22  rtc_tm.tm_min = 10; /* minute */
23  rtc_tm.tm_sec = 20; /* second */
24
25  if (ioctl(fd, RTC_SET_TIME, &rtc_tm) < 0) {
26      printf("RTC set time failed\n");
27      return -1;
28 }
29
30  return 0;
31 }
32
33 /* Read RTC time */
34 int read_rtc_time(int fd)
35 {
36  struct rtc_time rtc_tm;
37
38  if (ioctl(fd, RTC_RD_TIME, &rtc_tm) < 0) {
39      printf("RTC read time failed\n");
40      return -1;
41 }
42  printf("RTC time: %04d-%02d-%02d %02d:%02d:%02d\n",
43  rtc_tm_temp.tm_year + 1900, rtc_tm_temp.tm_mon + 1, rtc_tm_temp.tm_mday,
44  rtc_tm_temp.tm_hour, rtc_tm_temp.tm_min, rtc_tm_temp.tm_sec);
45
46  return 0;
47 }
48
49 int main(int argc, char *argv[])
50 {
51  int fd, ret;
52
53  /* Open RTC device */
54  fd = open(RTC_DEVICE_NAME, O_RDWR);
55  if (fd < 0) {
56      printf("Open rtc device %s failed\n", RTC_DEVICE_NAME);
57      return -ENODEV;
58 }
59
60 /* Set time */
61  ret = set_rtc_time(fd);
62  if (ret < 0)
63      return -EINVAL;
64
65 /* Read time */
66  ret = read_rtc_time(fd);
67  if (ret < 0)
68      return -EINVAL;
69
70  close(fd);
71  return 0;
72 }