Embedded Linux sets the time and date API, which is the source code that busybox to extract.
Steps for Linux to set the time and date:
1. Set the system time and date;
2. The system's time and date are synchronized to the hardware.
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <time.h> #include <linux/rtc.h> #include <linux/capability.h> int Setsysdateandtime (const char *time_str), void Sethwclockfromsysclock (int UTC), static int rtc_xopen (const char **default _RTC, int flags), static void Write_rtc (time_t T, int UTC), static const char *rtcname;int main (void) {const char time_str[] = "1989-11-22 11:22:33"; Setsysdateandtime (TIME_STR); Sethwclockfromsysclock (0); system ("reboot"); return 0;} int setsysdateandtime (const char *time_str) {struct TM Time_tm; struct Timeval time_tv; time_t timep;int ret;if (time_str = = NULL) {fprintf (stderr, "time string args invalid!\n"); return-1;} SSCANF (Time_str, "%d-%d-%d%d:%d:%d", &time_tm.tm_year, &time_tm.tm_mon, &time_tm.tm_mday, &time_ Tm.tm_hour, &time_tm.tm_min, &time_tm.tm_sec); Time_tm.tm_year-= 1900; Time_tm.tm_mon-= 1; Time_tm. tm_wday = 0; Time_tm.tm_yday = 0; time_tm.tm_isdst= 0; TIMEP = Mktime (&TIME_TM); Time_tv.tv_sec = TIMEP; time_tv.tv_usec = 0; ret = Settimeofday (&TIME_TV, NULL); if (ret! = 0) {fprintf (stderr, "Settimeofday failed\n"); Return-2; }return 0;} void Sethwclockfromsysclock (int UTC) {struct Timeval tv;gettimeofday (&TV, null);//if (Gettimeofday (&TV, NULL)) Bb_perror_msg_and_die ("Gettimeofday () failed"); Write_rtc (Tv.tv_sec, UTC);} static int Rtc_xopen (const char **DEFAULT_RTC, int flags) {int rtc;if (!*DEFAULT_RTC) {*DEFAULT_RTC = "/DEV/RTC"; RTC = Ope N (*DEFAULT_RTC, flags), if (RTC >= 0) return RTC;*DEFAULT_RTC = "/DEV/RTC0"; RTC = open (*DEFAULT_RTC, flags); if (RTC >= 0) return RTC;*DEFAULT_RTC = "/DEV/MISC/RTC";} Return open (*DEFAULT_RTC, flags);} static void Write_rtc (time_t T, int UTC) {#define RTC_SET_TIME_IOW (' P ', 0x0a, struct rtc_time)/* SET RTC Time */struct TM Tm;int RTC = Rtc_xopen (&rtcname, o_wronly); tm = * (UTC?)Gmtime (&t): LocalTime (&t)); TM.TM_ISDST = 0;ioctl (RTC, Rtc_set_time, &TM); close (RTC);}
Linux Setup system time and date API