Linux 下监测指定路径下指定时间间隔内是否有指定的文件的生成

来源:互联网 发布:线切割锥度编程 编辑:程序博客网 时间:2024/05/01 15:17

题目很拗口,感觉自己有必要说明一下,O(∩_∩)O~

在 Liunx 程序设计中,有时我们需要写这样一个程序,当指定目录下有相应的新文件生成时,触发程序动作,这个触发的动作可能是解析新生成的文件异或其他行为。

一种实现方法是在主程序中运行一个循环监测程序,监测指定目录下指定时间间隔内有没有指定的新文件生成,如果有则触发相应的解析动作等行为。

下面是自己写的一个脚本文件,功能就是做这样一件事情:

#!/bin/bash#program:#后台脚本,查找 path 路径下最近 n 秒内有没有新文件(文件名 filename )生成#path 脚本输入参数,查找路径#n 脚本输入参数,查找时间间隔(s)#filename 脚本输入参数,查找文件名#如果有生成,返回0;反之没有生成,返回1;脚本没有正常工作结束,返回2#History:#2011/06/11wwangfirst release# 获得当前世纪秒nowSoc=$(date +%s)# 输出#echo -e "Now time is $nowSoc..."# 判断脚本输入参数是否合法if test $# -eq 3; then# 设置查找路径path=$1# 设置查找时间间隔delta=$2# 自减delta秒nowSoc=$(($nowSoc - $delta))# 输出#echo -e "$nowSoc"# 设置查找文件名filename=$3# 查找控制输出文件theControlFile=$(find $path -name $filename)if [ -f "$theControlFile" ]; then# 输出#echo -e "The new Control file is $theControlFile..."# 获得文件的修改时间theFileChangeSoc=$(stat -c "%Z" $theControlFile)# 输出#echo -e "The file change time is $theFileChangeSoc..."# 判断最近 n 秒内是否生成了对应文件if test $(($theFileChangeSoc - $nowSoc)) -ge 0; then# 输出#echo -e "Find"# 返回 0exit 0else# 输出#echo -e "Not Find"# 返回 1exit 1fielse# 输出#echo -e "This is no new Control file..."# 返回 1exit 1fielse# 输出echo -e "This is no three parameters..."# 返回 2exit 2fi


下面是自己的调用示例,采用了 System 函数进行脚本调用,System 函数的相应知识可以参阅我的上一篇博客。

#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>// 可不需要包含//#include <sys/types.h>int main(){pid_t status;/* 功能:调用后台脚本,查找 path 路径下最近 n 秒内有没有新文件(文件名 filename )生成调用事例:脚本路径/findTheNewFile.sh path n filenamepath 脚本输入参数,查找路径n 脚本输入参数,查找时间间隔(s)filename 脚本输入参数,查找文件名脚本返回:如果有生成,返回0;反之没有生成,返回1;脚本没有正常工作结束,返回2 */status = system("./findTheNewFile.sh . 2 voltgecontroloutput.txt");/* 脚本调用失败 */if (-1 == status)        {            printf("system error!\n");        }        else       {            //printf("exit status value = [0x%x]\n", status);                // 判断脚本是否执行成功        if (WIFEXITED(status))            {            // 脚本正确返回            if (0 == WEXITSTATUS(status))                {                    printf("run shell script successfully, and find the new Control file.\n");                }               else if (1 == WEXITSTATUS(status))            {            printf("run shell script successfully, but not find the new Control file.\n");                }             else /*if (2 == WEXITSTATUS(status))*/               {                    printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status));                }            }            else            {                printf("exit status = [%d]\n", WEXITSTATUS(status));            }        }  return 0;}



原创粉丝点击