2014-02-08 34 views
1

我試圖使用inotify使用監視對文件的更改/dev/hvc0如下:inotify真的可以用於文件或僅用於目錄嗎?

#include <stdio.h> 
#include <sys/inotify.h> 
#include <stdlib.h> 

#define EVENT_SIZE (sizeof(struct inotify_event)) 
#define BUF_LEN  (1024 * (EVENT_SIZE + 16)) 
#define WATCH_FILE "/dev/hvc0" /* This file should be present 
            before this program is run */ 

int main() { 
    int notify_fd; 
    int length; 
    int i = 0; 
    char buffer[BUF_LEN]; 
    notify_fd = inotify_init(); 
    if (notify_fd < 0) { 
     perror("inotify_init"); 
    } 
    int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS); 
    int length_read = read(notify_fd, buffer, BUF_LEN); 
    if (length_read) { 
     perror("read"); 
    } 
    while (i < length_read) { 
     struct inotify_event *event = 
      (struct inotify_event *) &buffer[i]; 
     if (event->len) { 
      if (event->mask & IN_ACCESS) { 
       printf("The file %s was accessed.\n", event->name); 
      } else if (event->mask & IN_MODIFY) { 
       printf("The file %s was modified.\n", event->name); 
      } 
     } 
    } 

    (void) inotify_rm_watch(notify_fd, wd); 
    (void) close(notify_fd); 
    return 0; 
} 

但是,如果文件被訪問/修改,這並不打印。但是,無論何時將要監視的路徑更改爲目錄並更改了文件,它都會打印出發生的正確事件。

inotify是否也用於監視文件更改?或者我做錯了什麼?

謝謝!

+1

你能再次只是評論檢查長'if(event-> len)'語句用於測試命令。 –

+0

@JKB:gr8,現在工作!但爲什麼'event-> len' 0? o.O – jobin

回答

0

我不明白爲什麼event->len返回零可能是因爲沒有返回文件名。但只是爲了測試目的,您只需評論它。並在第二點 您對我的處理已損壞,您不會在循環中將其重置爲0。這將導致被視爲任何後來inotify事件,只有當他們比他們之前的最長的事件,這是不太可能你want.And請什麼while循環請把i += EVENT_SIZE + event->len;

int main() { 
    int notify_fd; 
    int length; 
    int i = 0; 
    char buffer[BUF_LEN]; 
    notify_fd = inotify_init(); 
    if (notify_fd < 0) { 
     perror("inotify_init"); 
    } 
    int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS); 
    while(1) 
    { 
     length = read(notify_fd, buffer, BUF_LEN); 

     if (length < 0) { 
      perror("read"); 
     } 

     while (i < length) 
     { 
      struct inotify_event *event = 
      (struct inotify_event *) &buffer[i]; 
      // if (event->len) { 
      if (event->mask & IN_ACCESS) { 
       printf("The file %s was accessed.\n", event->name); 
      } else if (event->mask & IN_MODIFY) { 
       printf("The file %s was modified.\n", event->name); 
      } 
      // } 
      i += EVENT_SIZE + event->len; 
     } 
    } 

    (void) inotify_rm_watch(notify_fd, wd); 
    (void) close(notify_fd); 

    exit(0); 
} 
+0

即使我將i重置爲0,我也想持續監視更改,程序在更改後終止。 – jobin

+0

請檢查我的更新答案。 –

1

您缺少增加i。在循環結束前添加:

i += EVENT_SIZE + event->len; 

如果要監視更改,還需要在無限循環中包裝讀取/打印操作。

+0

按照您所說的編輯代碼和問題(我實際上不需要修改創建和刪除;僅用於訪問/修改)來檢查訪問/修改,仍然不打印文件的事件。 – jobin

+0

檢查我的更新。我更好地解釋了它。它們是,作爲'inotify_add_watch'參數給出的路徑必須存在才能使該函數正常工作。這就是爲什麼你可以跟蹤創建一個文件,只有通過觀看包含文件夾 – hek2mgl

+0

我實際上只需要監視訪問/修改,已編輯的代碼和問題,但我沒有相同的事件通知。 – jobin

相關問題