【问题标题】:Missing notifications for /dev/sdX when using inotify使用 inotify 时缺少 /dev/sdX 的通知
【发布时间】:2017-12-01 07:17:45
【问题描述】:

我想在硬盘/硬盘分区上的数据被修改时得到通知。我在 Linux 上,希望它从 C++ 中检查。

我的方法是在 linux 设备文件 /dev/sdX 上使用 inotify(sdX = 适当的硬盘/磁盘分区文件)。我为 /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,但没有有用的答案。

【问题讨论】:

    标签: c++ linux hard-drive inotify


    【解决方案1】:

    /dev/sda1 是块设备,而不是常规文件。 inotify 无法观察设备进行修改。 (想想这对其他类型的设备意味着什么,比如/dev/random...)

    如果您想查看文件系统上的任何更改,请改用fanotify

    【讨论】:

    • 那么 fanotify 是否能够观察设备文件进行修改?每当我在挂载目录中添加/删除/编辑文件/目录时,我是否可以期望它通知修改?
    • 不是设备文件,但它可以一次观察整个文件系统的变化。 (哪个更好,因为并非所有文件系统都由设备支持。)阅读我链接的文档。
    • 我目前正在研究 RAID。所以,我需要通知修改特定的外部硬盘/硬盘分区。该硬盘分区可能未安装为文件系统。所以,观察一个挂载的文件系统对我没有用。
    • @YogirajKulkarni 那你就不走运了。没有用于观察块设备变化的用户空间界面; Linux 中已经存在的 RAID 实现(有几个!)都在内核中。
    • 不要认为所有的 RAID 实现都在内核中。我知道 MDADM,它是一个用 C 编写的 Linux 实用程序。我刚刚从 github repo 下载了它的源代码,编译它(使用 Makefile)并且我能够运行它。因此,似乎在应用程序级别也是可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多