歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言實現文件實時更新

C語言實現文件實時更新

日期:2017/3/1 9:20:50   编辑:Linux編程

一、簡介

在Linux或者Unix操作系統中在系統引導的時候會開啟很多服務,這些服務就叫做守護進程。 守護進程脫離了終端並且在後台運行:守護進程脫離於終端是為了避免進程在執行過程中的信息在任何終端上顯示並且進程也不會被任何終端所產生的終端信息所打斷。 本文介紹使用守護進程實現文件實時更新的方法步驟。

二、源碼

文件1:Realtime_Update.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>

void init_daemon(void);
static inline int timespec_compare(const struct timespec *lhs, const struct timespec *rhs);

/**
* 文件更新實時檢測程序
*/
main()
{
int ret;
struct stat statbuff_file1;
struct stat statbuff_file2;
char *file1 = "~/test_file1.txt";
char *file2 = "~/test_file2.txt";

stat(file1, &statbuff_file1);
stat(file2, &statbuff_file2);

//初始化為Daemon
init_daemon();

//循環執行,每秒一次
while(1)
{
//判斷文件是否更新
ret = timespec_compare(&statbuff_file1.st_mtim, &statbuff_file2.st_mtim);
if(ret > 0)
{
system("cp -a ~/test_file1.txt ~/test_file2.txt");
}

sleep(1);//睡眠一秒鐘
}
}

/**
* lhs < rhs: return <0
* lhs == rhs: return 0
* lhs > rhs: return >0
*/
static inline int timespec_compare(const struct timespec *lhs, const struct timespec *rhs)
{
if (lhs->tv_sec < rhs->tv_sec)
return -1;
if (lhs->tv_sec > rhs->tv_sec)
return 1;
return lhs->tv_nsec - rhs->tv_nsec;
}

文件2:init.c

#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>

void init_daemon(void)
{
int pid;
int i;

if(pid=fork())
exit(0);//是父進程,結束父進程
else if(pid< 0)
exit(1);//fork失敗,退出

//是第一子進程,後台繼續執行
setsid();//第一子進程成為新的會話組長和進程組長
//並與控制終端分離
if(pid=fork())
exit(0);//是第一子進程,結束第一子進程
else if(pid< 0)
exit(1);//fork失敗,退出

//是第二子進程,繼續
//第二子進程不再是會話組長
for(i=0; i< NOFILE; ++i) //關閉打開的文件描述符
close(i);
chdir("/tmp");
umask(0);//重設文件創建掩模
return;
}

編譯

gcc -o Realtime_Update init.c Realtime_Update.c

運行

./Realtime_Update

三、源碼下載

------------------------------------------分割線------------------------------------------

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2015年資料/11月/11日/C語言實現文件實時更新/

下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm

------------------------------------------分割線------------------------------------------

Copyright © Linux教程網 All Rights Reserved