Linux Application layer system time to write RTC Clock method

Source: Internet
Author: User
Tags local time

Linux kernel version: linux-3.0.35
Development Board: I. Mx6s my-imx6-ek200
System: UBUNTU12
Preface: Before writing a blog about how to read the system time through the application layer program, write a blog about how to write and save the RTC clock today.
One, write time
1. Preliminary knowledge:
A, Mktime
header File#include <time.h>
functiontime_t mktime(struct tm *timeptr)
function Description: Mktime () replaces the TM structure data referred to by TIMEPTR with the number of seconds elapsed from the local time since January 1, 1970 0:0 0 seconds.
return value: Returns the number of seconds elapsed. When an error occurs, return-1.
B, Settimeofday
header File#include <sys/time.h>
#include <unistd.h>
function: int settimeofday (const struct timeval *tv,const struct timezone *tz)
function Description: Settimeofday () sets the current time to the structure information referred to by TV, and the local time zone information is set to the structure that TZ refers to.
return value: Only root permissions can be used to modify the time of this function. The success returns 0, the failure returns 1, and the error code is stored in errno.
2. Practice:
With Mktime and Settimeofday, the time can be written.
3, the code is as follows:

#include <stdio.h>#include <time.h>#include <sys/time.h>#include <unistd.h>#include <stdlib.h>#include <bits/types.h>#include <linux/rtc.h>structmy_timeval{__time_t tv_sec; __suseconds_t tv_usec;};/************************************************** function Name: system_settime* function: Write system time * How to use:                   char* dt = "2016-04-15 21:00:00"; System_settime (DT); **************************************************/intSystem_settime (Char* DT) {structRtc_time TM;structTM _tm;structMy_timeval TV; time_t TIMEP;sscanf(DT,"%d-%d-%d%d:%d:%d", &tm.tm_year,&tm.tm_mon,&tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec);    _tm.tm_sec = tm.tm_sec;    _tm.tm_min = Tm.tm_min;    _tm.tm_hour = Tm.tm_hour;    _tm.tm_mday = Tm.tm_mday; _tm.tm_mon = Tm.tm_mon-1; _tm.tm_year = Tm.tm_year-1900;                                   TIMEP = Mktime (&AMP;_TM);    Tv.tv_sec = TIMEP; Tv.tv_usec =0;if(Settimeofday (&AMP;TV, (structTimeZone *)0) <0)    {printf("Set system datetime error!\n");return-1; }return 0;}voidMainvoid){Char*dt ="2016-4-15 21:00:00"; System_settime (DT);}

4. Test results:

Second, save time
as can be seen from the test results above, the system time can be written normally. I thought it would be OK at first, but I found it was no good. Because once I restart the Development Board, the system time will revert back to the original time. Think of it, we just wrote the system time, did not synchronize the system time to the hardware time, so that the system every time the hardware restart read time is unchanged, the system time to get started after the CST = UTC + 8, or the system time to exchange. How do we synchronize the system time we set to hardware time? We know that in the terminal, the system time can be synchronized to the hardware time through the HWCLOCK–SYSTOHC, how to achieve in the application layer? I don't know if there is any other good solution, I think out of the way is to create a sub-process in the application layer, in the sub-process to invoke the script file, the script is the instruction is HWCLOCK–SYSTOHC. This completes the synchronization. Of course, if there is a simpler and more appropriate way, welcome guidance, communication. So much to say.
1. Preliminary knowledge:
A, fork to create the sub-process, the code is as follows:

/*************************** Function: Create sub-process fork () test * Time: 2016-4-15* Author: Jack cui***************************/#include <unistd.h> #include <stdio.h>intMain (void) {pid_t fpid;//fpid represents the value returned by the fork function    intCount=0; Fpid=fork ();if(Fpid <0)//Create child process failedprintf"error\n");Else if(Fpid = =0) {printf ("I am the child process,my process ID is%d\n", Getpid ());    count++; }Else{printf ("I am the parent process,my process ID is%d\n", Getpid ());    count++; } printf ("Count =%d\n", count);return 0;}

b, the fork test program results show:

C, EXECVE () application layer invoke script file:
header file: #include <unistd.h>
function: int execve(const char * filename, char * const argv[], char * const envp[]);
function Description: execve () is used to execute the file path represented by the argument filename string, the second parameter is passed to the execution file using an array pointer, and the last parameter is an array of new environment variables passed to the execution file.
return Value: If the execution succeeds the function will not return, and the execution failure will return 1 directly, and the reason for failure is stored in errno.
D, Execve () test code:

/*************************** features: Test execve* Time: 2016-4-15* Author: Jack cui***************************/ #include <stdio.h> //perror  #include <stdlib.h> //exit_success exit_failure  # Include <unistd.h> //execve  void  Main ( Span class= "Hljs-keyword" >void ) {char  * args[] = {     "/home/nfsroot/hwclock.sh" , NULL}; if  (-1  = = (Execve (, args        , NULL)) {perror ( "Execve" );    Exit (Exit_failure); } exit (exit_success);}  

E, script content:

F, EXECVE Test results:

It can be seen that EXECVE is used normally, we can change the script content to HWCLOCK–SYSTOHC to realize the synchronization of the system time to the hardware time.
third, the overall code is as follows:

/******************************************* function: Linux application layer system time to write RTC Clock method * Time: 2016-4-15* Author: Jack cui************* ******************************/#include <stdio.h>#include <time.h>#include <sys/time.h>#include <unistd.h>#include <stdlib.h>#include <bits/types.h>#include <linux/rtc.h>structmy_timeval{__time_t tv_sec; __suseconds_t tv_usec;};/************************************************** function Name: system_settime* function: Write system time * Use method: Char                * dt = "2016-04-15 21:00:00"; System_settime (DT); **************************************************/intSystem_settime (Char* DT) {structRtc_time TM;structTM _tm;structMy_timeval TV; time_t TIMEP;sscanf(DT,"%d-%d-%d%d:%d:%d", &tm.tm_year,&tm.tm_mon,&tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec);    _tm.tm_sec = tm.tm_sec;    _tm.tm_min = Tm.tm_min;    _tm.tm_hour = Tm.tm_hour;    _tm.tm_mday = Tm.tm_mday; _tm.tm_mon = Tm.tm_mon-1; _tm.tm_year = Tm.tm_year-1900;                                   TIMEP = Mktime (&AMP;_TM);    Tv.tv_sec = TIMEP; Tv.tv_usec =0;if(Settimeofday (&AMP;TV, (structTimeZone *)0) <0)    {printf("Set system datetime error!\n");return-1; }return 0;}voidMainvoid){Char*dt ="2016-4-15 21:00:00"; pid_t Fpid;//fpid represents the value returned by the fork functionFpid=fork ();if(Fpid <0)//Create child process failed        printf("error\n");Else if(Fpid = =0)     {Char* args[] = {"/home/nfsroot/hwclock.sh", NULL};if(-1= = (Execve ("/home/nfsroot/hwclock.sh", Args,null))) {perror ("Execve");Exit(exit_failure); }Exit(exit_success); }Else{system_settime (dt); }return 0;}

Iv. The final results show:
1. Script content:

2. Test results:

so we restart the Development Board, the system time will not change, set the success!

Linux Application layer system time to write RTC Clock method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.