文件监控工具 inotify-tools
在Linux下载并安装工具 inotify-tools 。
Ubuntu 下安装:
sudo apt-get install inotify-tools
- 1
例子
假设工程文件都放在 src/ 中,并且想监控此文件夹中的所有文件变更、创建、删除操作,事件发生后可执行 mvn package
进行打包。
#!/bin/bash
cd `dirname $0`
rebuild() {
local build_lock="build.lock"
local pending_lock="pending.lock"
test -f $build_lock && {
echo "building is in process and waiting.." >&2
touch $pending_lock
exit 1
}
touch $build_lock
echo -------------------- rebuild
mvn package
echo -------------------- rebuild complete
rm $build_lock
test -f $pending_lock && {
rm $pending_lock
rebuild &
}
}
main() {
local folder="src/"
local file_4_changes="/tmp/watch"
while inotifywait -e create,modify,delete -r $folder -o $file_4_changes; do
rebuild &
done
}; main "$@"
文件的变更历史都在日志文件 /tmp/watch 中记录。
///***************************************************************
使用inotify来监控文件变化。inotify是基于事件的监控,无需定时轮询文件状态,也无需做内核模块hook系统调用,简单可靠。比较好的实现是检测到文件变化时,同时记录下当前登陆的用户以及当前用户启动的进程。不过inotify,需要kernel 2.6.13以上支持,RHEL5默认是有的,其它系统不确定。
比如:$ dnotify -rCDRM dragon_extfs/ -e echo hello&
监控dragon_extfs包括子目录下所有改动,当发生(C创建,D删除,R更名,M修改)等改变时执行命令echo hello
事件:
-A, --access 目标目录文件被访问
-M, --modify 目标目录文件被改变
-C, --create 目标目录文件被创建
-D, --delete 目标目录文件被删除
-R, --rename 目标目录文件被更名
-B, --attrib 目标目录文件被属性修改
-a, --all 以上所有事件
参数:
-e, --execute=COMMAND.. 执行命令 一般情况下-e为最后一个参数,-e之后为命令argv
-f, --file=FILE 监控一个文件目录列表
-p, --processes=COUNT max number of commands to run at a time
-q, --queue=DEPTH max depth of queue holding commands to be run
-t, --times=COUNT exit after running the command COUNT times
-o, --once same as `--times 1'
-r, --recursive 递归子目录
-b, --background 后台运行
-s, --silent 不打印信息
--quiet 同-s
--help display this help and exit
--version output version information and exit