2010-01-19 41 views
2

我有監視目錄(/測試)並通知我的程序。 我想改進它來監視另一個目錄(比如/ opt)。 還有如何監控它的子目錄,目前我會收到通知,如果任何更改/測試下的文件。但我沒有得到任何inotifcation如果所做的更改/測試的子目錄,這是觸摸/test/sub-dir/files.txt ..C程序使用inotify監視多個目錄以及子目錄?

這裏我當前的代碼 - 希望這將有助於

/* 

Simple example for inotify in Linux. 

inotify has 3 main functions. 
inotify_init1 to initialize 
inotify_add_watch to add monitor 
then inotify_??_watch to rm monitor.you the what to replace with ??. 
yes third one is inotify_rm_watch() 
*/ 


#include <sys/inotify.h> 

int main(){ 
    int fd,wd,wd1,i=0,len=0; 
    char pathname[100],buf[1024]; 
    struct inotify_event *event; 

    fd=inotify_init1(IN_NONBLOCK); 
    /* watch /test directory for any activity and report it back to me */ 
    wd=inotify_add_watch(fd,"/test",IN_ALL_EVENTS); 

    while(1){ 
     //read 1024 bytes of events from fd into buf 
     i=0; 
     len=read(fd,buf,1024); 
     while(i<len){ 
      event=(struct inotify_event *) &buf[i]; 


      /* check for changes */ 
      if(event->mask & IN_OPEN) 
       printf("%s :was opened\n",event->name); 

      if(event->mask & IN_MODIFY) 
       printf("%s : modified\n",event->name); 

      if(event->mask & IN_ATTRIB) 
       printf("%s :meta data changed\n",event->name); 

      if(event->mask & IN_ACCESS) 
       printf("%s :was read\n",event->name); 

      if(event->mask & IN_CLOSE_WRITE) 
       printf("%s :file opened for writing was closed\n",event->name); 

      if(event->mask & IN_CLOSE_NOWRITE) 
       printf("%s :file opened not for writing was closed\n",event->name); 

      if(event->mask & IN_DELETE_SELF) 
       printf("%s :deleted\n",event->name); 

      if(event->mask & IN_DELETE) 
       printf("%s :deleted\n",event->name); 

      /* update index to start of next event */ 
      i+=sizeof(struct inotify_event)+event->len; 
     } 

    } 

} 

回答

0

在inotify中,每個目錄需要一個手錶。對於全局通知,大概是這樣。

0

您可以嘗試刪除子文件夾,並在每次需要添加內容時重新創建它。

4

inotify_add_watch不偵聽子目錄中的更改。你必須檢測這些子目錄何時被創建,並且它們也是inotify_add_watch

最重要的是要注意的是,在創建子目錄之後,您會得到相應的通知,但在您收到通知時,文件和子目錄可能已經在該目錄內創建,因此你會「失去」這些事件,因爲你還沒有機會爲新的子目錄添加監視。

避免此問題的一種方法是在收到通知後掃描目錄內容,以便您可以看到那裏的內容。這爲他們增加更多手錶創造了機會。