1. 程式人生 > 實用技巧 >inotify-tool實時監控伺服器檔案狀態變化 學習總結

inotify-tool實時監控伺服器檔案狀態變化 學習總結

一、安裝Inotify-tools工具

1、檢視伺服器核心是否支援inotify

ll /proc/sys/fs/inotify #列出檔案目錄,出現下面的內容,說明伺服器核心支援inotify

-rw-r--r-- 1 root root 0 Mar 7 02:17 max_queued_events

-rw-r--r-- 1 root root 0 Mar 7 02:17 max_user_instances

-rw-r--r-- 1 root root 0 Mar 7 02:17 max_user_watches

備註:Linux下支援inotify的核心最小為2.6.13,可以輸入命令:uname -a檢視核心

CentOS 
5.X 核心為2.6.18,預設已經支援inotify

2、安裝inotify-tools

yum install make gcc gcc-c++ #安裝編譯工具

inotify-tools下載地址:https://udomain.dl.sourceforge.net/project/inotify-tools/inotify-tools/3.13/inotify-tools-3.13.tar.gz
上傳inotify-tools-3.13.tar.gz到/usr/local/src目錄下

cd /usr/local/src

tar zxvf inotify-tools-3.13.tar.gz #解壓

cd inotify
-tools-3.13 #進入解壓目錄 ./configure --prefix=/usr/local/inotify #配置 make #編譯 make install #安裝

3、設定系統環境變數,新增軟連線

echo "PATH=/usr/local/inotify/bin:$PATH" >>/etc/profile.d/inotify.sh

source /etc/profile.d/inotify.sh #使設定立即生效

echo "/usr/local/inotify/lib" >/etc/ld.so.conf.d/inotify.conf

ln -s /usr/local/inotify/include /usr/include/inotify

4、修改inotify預設引數(inotify預設核心引數值太小)


修改引數:

vi /etc/sysctl.conf #新增以下程式碼

fs.inotify.max_queued_events=99999999

fs.inotify.max_user_watches=99999999

fs.inotify.max_user_instances=65535

:wq! #儲存退出

引數說明:

max_queued_events:

inotify佇列最大長度,如果值太小,會出現"** Event Queue Overflow **"錯誤,導致監控檔案不準確

max_user_watches:

要同步的檔案包含多少目錄,可以用:find /home/www.osyunwei.com -type d | wc -l 統計,必須保證max_user_watches值大於統計結果(這裡/home/www.osyunwei.com為同步檔案目錄)

max_user_instances:

每個使用者建立inotify例項最大值

二、建立實時監控指令碼

mkdir -p /home/inotify #建立目錄

vi /home/inotify/inotif.sh #編輯

#!/bin/sh

srcdir=/var/jenkins_home/workspace/build_java/

inotifywait -mrq --timefmt '%d/%m/%y-%H:%M' --format '%T%w%f' -e attrib ${srcdir} \
| while read file

do

echo "hahhahahha"

done

三、問題處理

1.inotify報錯upper limit on inotify watches reached

cat一下這個檔案,預設值是8192,echo 8192000 > /proc/sys/fs/inotify/max_user_watches即可~