一、简介

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

三、源码下载

05-11 16:16
查看更多