2017-06-28 64 views
1

我想在硬盤/硬盤分區上的數據被修改時收到通知。我在Linux上,並希望它從C++中檢查。使用inotify時缺少/ dev/sdX的通知

我的方法是在Linux設備文件/ dev/sdX(s​​dX =適當的硬盤/磁盤分區文件)上使用inotify。我爲/ dev/sda1文件編寫了程序。我的期望是,無論何時在主目錄中的任何位置創建/刪除文件/文件夾,文件/ dev/sda1都應該動態修改(因爲我的/ dev/sda1安裝在位置「/」),我應該得到修改通知。但是,我沒有收到通知。

這裏是我的代碼: -

#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <sys/types.h> 
#include <sys/inotify.h> 
#include <unistd.h> 

#define EVENT_SIZE (sizeof (struct inotify_event)) 
#define BUF_LEN  (1024 * (EVENT_SIZE + 16)) 

const char * file_path = "/dev/sda1"; 

int main(int argc, char **argv) 
{ 
    int length, i; 
    int fd; 
    int wd; 
    char buffer[BUF_LEN]; 


    while(1) 
    { 

    fd = inotify_init(); 

    if (fd < 0) { 
     perror("inotify_init"); 
    } 

    wd = inotify_add_watch(fd, file_path, IN_MODIFY); 

    if (wd < 0) 
      perror ("inotify_add_watch"); 


     length = read(fd, buffer, BUF_LEN); 

     printf("here too\n"); 

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

      i = 0; 

     while (i < length) { 
      struct inotify_event *event = (struct inotify_event *) &buffer[ i ]; 
      printf("inotify event\n"); 


     if (IN_MODIFY) { 
      if (event->mask & IN_ISDIR) { 
        printf("The directory %s was modified.\n", file_path); 
      } 
       else { 
        printf("The file %s was modified.\n", file_path); 
       } 
      } 

      i += EVENT_SIZE + event->len; 

     } 

     (void) inotify_rm_watch(fd, wd); 
     (void) close(fd); 
    } 



    exit(0); 
} 

此代碼爲通知正確只要文件被修改的一個正常的文件。但是,只要相應的設備掛載目錄發生更改,它就不能在設備文件上運行。我的方法有什麼問題嗎?不管動態修改/ dev/sdX文件,每當裝入它的文件系統被更改?

我發現了一個類似的問題Get notified about the change in raw data in hard disk sector - File change notification,但沒有有用的答案。

回答

1

/dev/sda1是一個塊設備,而不是一個普通的文件。 inotify不能觀察設備進行修改。 (考慮這對於其他類型的設備甚至意味着什麼,例如/dev/random ...)

如果要觀察文件系統上的任何更改,請改爲使用fanotify

+0

請fanotify能夠觀察設備文件的修改嗎?我是否可以期望它在每次在其所在的目錄中添加/刪除/編輯文件/目錄時通知修改? –

+0

不是設備文件,但它可以一次觀察整個文件系統進行更改。 (哪個更好,因爲並非所有文件系統都支持設備。)請閱讀我鏈接的文檔。 – duskwuff

+0

我目前正在使用RAID。所以,我需要通知修改特定的外部硬盤/硬盤分區。該硬盤分區可能未被安裝爲文件系統。所以,觀察一個安裝的文件系統對我來說沒有用處。 –