加入收藏 | 设为首页 | 会员中心 | 我要投稿 应用网_丽江站长网 (http://www.0888zz.com/)- 科技、建站、数据工具、云上网络、机器学习!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

C语言达成文件实时更新

发布时间:2021-11-19 10:36:32 所属栏目:PHP教程 来源:互联网
导读:一、简介 在Linux或者Unix操作系统中在系统引导的时候会开启很多服务,这些服务就叫做守护进程。 守护进程脱离了终端并且在后台运行:守护进程脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。

一、简介
 
在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
 
三、源码下载

(编辑:应用网_丽江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读