一、简介

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

三、源码下载

最新文章

  1. django静态文件配置
  2. Lambda GroupBy Sum
  3. Installing Oracle and ArcSDE on separate servers
  4. java中几种常见字符集与乱码介绍
  5. SQL语句的执行计划(oracle表的三种链接方式)
  6. Java正确转换html编码
  7. vector 与map的下标操作
  8. Mesos编译步骤及部署注意事项(Ubuntu)
  9. FineUI开发实践-目录
  10. [c#]asp.net开发微信公众平台(2)多层架构框架搭建和入口实现
  11. 抓取数据同步备份hive
  12. UIKit控件直接显示网页文字内容
  13. APP热更新方案
  14. Spring MVC知识点整理
  15. 》》初识移动端--rem
  16. RobotFramework第一篇之环境搭建
  17. Scrapy详解
  18. linux设置自启动redis
  19. 换了电脑如何使用hexo继续写博客
  20. NOIP 2006 作业调度方案

热门文章

  1. Git学习--版本回退
  2. mysql1130远程连接没有权限的解决方法
  3. python使用 db.select 返回的数据只能遍历一次
  4. CANopenSocket 测试
  5. MySQL实战 | 06/07 简单说说MySQL中的锁
  6. loj 6083.「美团 CodeM 资格赛」数码
  7. spark 单机版安装
  8. 高性能服务器架构 的几个注意点 (High-Performance Server Architecture)
  9. QT QString与char *之间的转换 【转载】
  10. 动态规划算法(后附常见动态规划为题及Java代码实现)