Linux内核从2.6.13开始,引入了inotify机制。通过intofity机制,能够对文件系统的变化进行监控,如对文件进行创建、删除、修改等操作,可以及时通知应用程序进行相关事件的处理。这种响应处理机制,避免了频繁的文件轮询任务,提高了任务的处理效率。
一、检查安装
检查系统内核版本
检查系统是否支持inotify
# ls -lsart /proc/sys/fs/inotify
total 0
0 dr-xr-xr-x 0 root root 0 Sep 19 09:38 ..
0 -rw-r--r-- 1 root root 0 Jan 1 13:51 max_user_watches
0 -rw-r--r-- 1 root root 0 Jan 1 13:51 max_user_instances
0 -rw-r--r-- 1 root root 0 Jan 1 13:51 max_queued_events
0 dr-xr-xr-x 0 root root 0 Jan 1 13:51 .
如果出现上面结果说明系统支持inotify
notify是一个API,需要通过开发应用程序进行调用,对于大多数用户来讲这有着许多不便,inotify-tools的出现弥补了这一不足。
inotify-tools是一套组件,它包括一个C库和几个命令行工具,这些命令行工具可用于通过命令行或脚本对某文件系统的事件进行监控。
下载安装
#wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
# tar -zvxf inotify-tools-3.14.tar.gz
# cd inotify-tools-3.14
[root@ inotify-tools-3.14]# ./configure --prefix=/usr/local/inotify
[root@ inotify-tools-3.14]# make
[root@ inotify-tools-3.14]# make install
或者使用yum
yum install inotify-tools
其它的一些notify工具(参考)
inotify 的实现有几款软件
1)inotify-tools,
2)sersync(金山周洋)
3)lsyncd
二、命令讲解
inotify-tools提供的两个命令行工具:
inotifywait:通过inotify API等待被监控文件上的相应事件并返回监控结果
默认情况下,正常的结果返回至标准输出,
诊断类的信息则返回至标准错误输出。
它可以在监控到对应监控对象上指定的事件后退出,也可以进行持续性的监控。
inotifywatch:通过inotify API收集被监控文件或目录的相关事件并输出统计信息。
inotifywait:
常用参数:
--timefmt 时间格式 %y年 %m月 %d日 %H小时 %M分钟
--format 输出格式 %T时间 %w路径 %f文件名 %e状态
-m --monitor 始终保持监听状态;默认触发事件即退出。
-r --recursive 递归查询目录
-q 打印出监控事件
-e --event 定义监控的事件,可用参数:
Events:
access file or directory contents were read 文件读取
modify file or directory contents were written 文件更改
attrib file or directory attributes changed 文件属性更改
close_write file or directory closed, after being opened in 以只读模式打开的文件被关闭
writeable mode
close_nowrite file or directory closed, after being opened in 以只读模式打开的文件被关闭
read-only mode
close file or directory closed, regardless of read/write mode 文件被关闭,不管它是如何打开的
open file or directory opened
moved_to file or directory moved to watched directory 移入监听目录 即使是在同一目录内移动,此事件也触发
moved_from file or directory moved from watched directory 移除监听目录 即使是在同一目录内移动,此事件也触发
move file or directory moved to or from watched directory 包括moved_to和 moved_from
create file or directory created within watched directory
delete file or directory delete