使用inotify时缺少/ dev / sdX的通知

时间:2017-06-28 04:40:15

标签: c++ linux hard-drive inotify

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

我的方法是在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 个答案:

答案 0 :(得分:2)

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

如果您想观察文件系统的任何更改,请改用fanotify