Skip to content

Instantly share code, notes, and snippets.

@mikolasan
Created September 28, 2023 21:54
Show Gist options
  • Save mikolasan/06af9e595ae25d9993241f011d9ad8b8 to your computer and use it in GitHub Desktop.
Save mikolasan/06af9e595ae25d9993241f011d9ad8b8 to your computer and use it in GitHub Desktop.
RTC set time overflow after January 1, 2070
// Compile:
// gcc -o test_ioctl_tm_struct test_ioctl_tm_struct.c
// Run on Linux:
// ./test_ioctl_tm_struct
// Expected output:
// RTC time set successfully.
//
// Actual result:
// Failed to set RTC time: Invalid argument
//
// Notes:
// Originally caused by `hwclock --systohc`
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
int main() {
int rtc_fd;
struct rtc_time rtc_tm;
// Open the real-time clock device
rtc_fd = open("/dev/rtc0", O_RDWR);
if (rtc_fd == -1) {
perror("Failed to open RTC device");
return 1;
}
// Set the time structure
rtc_tm.tm_sec = 0;
rtc_tm.tm_min = 0;
rtc_tm.tm_hour = 0;
rtc_tm.tm_mday = 1;
rtc_tm.tm_mon = 0; // January (0-indexed)
rtc_tm.tm_year = 170; // Years since 1900
rtc_tm.tm_wday = 0;
rtc_tm.tm_yday = 0;
rtc_tm.tm_isdst = 0;
// Use ioctl to set the RTC time
if (ioctl(rtc_fd, RTC_SET_TIME, &rtc_tm) == -1) {
perror("Failed to set RTC time");
close(rtc_fd);
return 1;
}
printf("RTC time set successfully.\n");
// Close the RTC device
close(rtc_fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment