First, Introduction
Many services are turned on in Linux or UNIX operating systems when the system is booted, and these services are called daemons. The daemon is out of the terminal and running in the background: The daemon is detached from the terminal to prevent the process from displaying information on any terminal and the process is not interrupted by terminal information generated by any terminal. This article describes the steps for using daemons to implement real-time file updates.
Second, the source code
File 1:realtime_update.c
#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<time.h>#include<fcntl.h>#include<sys/stat.h>voidInit_daemon (void);StaticInlineintTimespec_compare (Const structTimespec *LHS,Const structTimespec *RHS);/** * File update real-time detection program*/Main () {intret; structstat statbuff_file1; structstat statbuff_file2; Char*file1 ="~/test_file1.txt"; Char*file2 ="~/test_file2.txt"; Stat (File1,&statbuff_file1); Stat (File2,&statbuff_file2); //Initialize to daemonInit_daemon (); //loop execution, once per second while(1) { //determine if the file is updatedret = Timespec_compare (&statbuff_file1.st_mtim, &Statbuff_file2.st_mtim); if(Ret >0) {System ("cp-a ~/test_file1.txt ~/test_file2.txt"); } Sleep (1);//sleep for a second }}/** * LHS < rhs:return <0 * LHS = rhs:return 0 * lhs > Rhs:return >0*/StaticInlineintTimespec_compare (Const structTimespec *LHS,Const structTimespec *RHS) { if(Lhs->tv_sec < rhs->tv_sec)return-1; if(Lhs->tv_sec > rhs->tv_sec)return 1; returnLhs->tv_nsec-rhs->tv_nsec;}
File 2:init.c
#include <stdlib.h>#include<unistd.h>#include<signal.h>#include<sys/param.h>#include<sys/types.h>#include<sys/stat.h>voidInit_daemon (void){ intpid; inti; if(pid=Fork ()) Exit (0);//is the parent process that ends the parent process Else if(pid<0) Exit (1);//Fork failed, exit//is the first child process, the background continues to executeSetsid ();//the first child process becomes the new conversation leader and process leader//and separated from the control terminal if(pid=Fork ()) Exit (0);//is the first child process, ending the first child process Else if(pid<0) Exit (1);//Fork failed, exit//is the second child process, continue//The second child process is no longer a conversation leader for(i=0; i< Nofile; ++i)//Close Open File descriptorClose (i); ChDir ("/ tmp"); Umask (0);//resetting file creation masks return;}
Compile
gcc -o realtime_update init.c realtime_update.c
Run
./realtime_update
Third, the source code download
http://files.cnblogs.com/files/274914765qq/realtime_update_daemon.zip
Reference: http://www.cnblogs.com/274914765qq/p/4792707.html
C language implementation of real-time file updates