簡介: 當需要對 Linux®文件系統進行高效率、細粒度、異步地監控時,可以采用 inotify。可利用它對用戶空間進行安全、性能、以及其他方面的監控。
至於inotify的基本介紹可以看下面鏈接
http://www.ibm.com/developerworks/cn/linux/l-inotify/index.html?ca=drs-
這里主要說下自己試驗的總結:
- 何時需要自己調用inotify_rm_watch
- 合適需要自己調用inotify_add_watch
- read調用注意事項
對於1,出現moved_from而沒有出現moved_to時,這就需要自己調用inotify_rm_watch把移走的文件目錄(移到非監控目錄下)監控刪除,這個目錄下面的子目錄會自動刪除的 。像其它操作:刪除監控目錄,監控目錄在大的監控目錄下移進移出是不需要自己調用inotify_rm_watch的,因為系統自動處理,產生的事件分別為delete_self和move_self。
對於2, 這要看你是否需要遞歸監控每個目錄,如果是,那么當你在監控目錄下建立一個新目錄時,就需要調用inotify_add_watch;放心系統不會出現單獨的moved_to, 如果你從非監控目錄下copy一個目錄到監控目錄下,那么inotify產生的事件是create (目錄或文件),而不會是moved_to的,但可以單獨產生moved_from事件,如情況1所說。
對與3,要知道下面紅色的限制,
/proc interfaces
The following interfaces can be used to limit the amount of kernel memory consumed by inotify:
/proc/sys/fs/inotify/max_queued_events
The value in this file is used when an application calls inotify_init(2) to set an upper limit on the number of events that can be queued to the corresponding inotify instance. Events in excess of this limit are dropped, but an N_Q_OVERFLOW event is always generated.
/proc/sys/fs/inotify/max_user_instances
This specifies an upper limit on the number of inotify instances that can be created per real user ID.
/proc/sys/fs/inotify/max_user_watches
This specifies an upper limit on the number of watches that can be created per real user ID.
如果你監控的目錄很大,那么其它限制你也必須考慮,調用read時,要注意返回的是一個完整的
struct inotify_event {
int wd; /* Watch descriptor */
uint32_t mask; /* Mask of events */
uint32_t cookie; /* Unique cookie associating related
events (for rename(2)) */
uint32_t len; /* Size of name field */
char name[]; /* Optional null-terminated name */
};
結構。