我們在開發程序的時候會遇到很多問題,通常程序員都會加上監控目錄和目錄的子目錄這個功能,下面武林技術頻道小編就給大家介紹詳解Inotify 監控目錄與文件的操作方法,一起來看看吧!
1. 監控路徑并打印所有發生在該路徑的事件.
代碼如下:
?
?
?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_NUM 12
char *event_str[EVENT_NUM] =
{
?"IN_ACCESS",
?"IN_MODIFY",
?"IN_ATTRIB",
?"IN_CLOSE_WRITE",
?"IN_CLOSE_NOWRITE",
?"IN_OPEN",
?"IN_MOVED_FROM",
?"IN_MOVED_TO",
?"IN_CREATE",
?"IN_DELETE",
?"IN_DELETE_SELF",
?"IN_MOVE_SELF"
};
int main(int argc, char *argv[])
{
?int fd;
?int wd;
?int len;
?int nread;
?char buf[BUFSIZ];
?struct inotify_event *event;
?int i;
?if(argc < 2)
?{
??fprintf(stderr, "%s path/n", argv[0]);
??return -1;
?}
?fd = inotify_init();
?if( fd < 0 )
?{
??fprintf(stderr, "inotify_init failed/n");
??return -1;
?}
?wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);
?if(wd < 0)
?{
??fprintf(stderr, "inotify_add_watch %s failed/n", argv[1]);
??return -1;
?}
?buf[sizeof(buf) - 1] = 0;
?while( (len = read(fd, buf, sizeof(buf) - 1)) > 0 )
?{
??nread = 0;
??while( len > 0 )
??{
???event = (struct inotify_event *)&buf[nread];
???for(i=0; i<EVENT_NUM; i++)
???{
????if((event->mask >> i) & 1)
????{
?????if(event->len > 0)
??????fprintf(stdout, "%s --- %s/n", event->name, event_str[i]);
?????else
??????fprintf(stdout, "%s --- %s/n", " ", event_str[i]);
????}
???}
???nread = nread + sizeof(struct inotify_event) + event->len;
???len = len - sizeof(struct inotify_event) - event->len;
??}
?}
?return 0;
}
運行 inotify_watch 監控一個目錄:
?
?
?
$ ./inotify_watch test/
...
? --- IN_OPEN
? --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swpx --- IN_CREATE
.tmp.swpx --- IN_OPEN
.tmp.swpx --- IN_CLOSE_WRITE
.tmp.swpx --- IN_DELETE
.tmp.swp --- IN_CLOSE_WRITE
.tmp.swp --- IN_DELETE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swp --- IN_MODIFY
? --- IN_OPEN
? --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_MODIFY
...
從上面的結果可以看到在 test 目錄中使用 vim 創建一個 tmp 文件, 產生很多的冗雜事件. 因此需要對監控的事件做出小范圍的選擇而不是 IN_ALL_EVENTS .
2. IN_MOVE_SELF 和 IN_DELETE_SELF 事件
由于個人水平, 曾經對這兩個事件的含義并沒有理解正確. 當監控 path 時( path可以是文件或目錄),
?
?
?
$ ./inotify_watch path
執行
?
?
?
$ rm -f path
則發生 IN_DELETE_SELF 事件;
執行
?
?
?
mv path path2
則發生 IN_MOVE_SELF 事件.
3. 監控目錄和文件
監控目錄中內容改變應監控的事件:
?
?
IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVDED_TO
監控文件內容的改變應監控的事件:
?
?
?
IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF
通過上面的介紹,想必大家已經知道了詳解Inotify 監控目錄與文件的操作方法,看完文章的朋友會對這方面的知識有更多了解,希望武林技術頻道小編的介紹對大家有幫助。