易网时代-编程资源站
Welcome
微信登录
首页
/
操作系统
/
Linux
/
Linux 下监测指定路径下指定时间间隔内是否有指定的文件的生成
题目很拗口,感觉自己有必要说明一下,O(∩_∩)O~在 Liunx 程序设计中,有时我们需要写这样一个程序,当指定目录下有相应的新文件生成时,触发程序动作,这个触发的动作可能是解析新生成的文件异或其他行为。一种实现方法是在主程序中运行一个循环监测程序,监测指定目录下指定时间间隔内有没有指定的新文件生成,如果有则触发相应的解析动作等行为。下面是自己写的一个脚本文件,功能就是做这样一件事情:
#!/bin/bash
#program:
# 后台脚本,查找 path 路径下最近 n 秒内有没有新文件(文件名 filename )生成
# path 脚本输入参数,查找路径
# n 脚本输入参数,查找时间间隔(s)
# filename 脚本输入参数,查找文件名
# 如果有生成,返回0;反之没有生成,返回1;脚本没有正常工作结束,返回2
#History:
# 2011/06/11 wwang first 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"
# 返回 0
exit 0
else
# 输出
#echo -e "Not Find"
# 返回 1
exit 1
fi
else
# 输出
#echo -e "This is no new Control file..."
# 返回 1
exit 1
fi
else
# 输出
echo -e
"This is no three parameters..."
# 返回 2
exit 2
fi
下面是自己的调用示例,采用了 System 函数进行脚本调用,System 函数的相应知识可以参阅这篇文章 http://www.linuxidc.com/Linux/2011-09/42425.htm 。
#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 filename
path 脚本输入参数,查找路径
n 脚本输入参数,查找时间间隔(s)
filename 脚本输入参数,查找文件名
脚本返回:如果有生成,返回0;
反之没有生成,返回1;
脚本没有正常工作结束,返回2
*/
status = system(
"./findTheNewFile.sh . 2 voltgecontroloutput.txt"
);
/* 脚本调用失败 */
if
(-1 == status)
{
printf(
"system error! "
);
}
else
{
//printf("exit status value = [0x%x] ", status);
// 判断脚本是否执行成功
if
(WIFEXITED(status))
{
// 脚本正确返回
if
(0 == WEXITSTATUS(status))
{
printf(
"run shell script successfully, and find the new Control file. "
);
}
else
if
(1 == WEXITSTATUS(status))
{
printf(
"run shell script successfully, but not find the new Control file. "
);
}
else
/*if (2 == WEXITSTATUS(status))*/
{
printf(
"run shell script fail, script exit code: %d "
, WEXITSTATUS(status));
}
}
else
{
printf(
"exit status = [%d] "
, WEXITSTATUS(status));
}
}
return
0;
}
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图