Yogiraj
Yogiraj

Reputation: 328

Missing notifications for /dev/sdX when using inotify

I want to get notified whenever data on hard disk / hard disk partition gets modified. I am on Linux and want it to check from C++.

My approach was to use inotify on linux device file /dev/sdX (sdX = appropriate hard disk / disk partition file). I wrote program for /dev/sda1 file. My expectation was that whenever I create/delete a file/folder anywhere in home directory, the file /dev/sda1 should dynamically get modified (since my /dev/sda1 is mounted at location "/") and I should get notified for modification. But, I did not get notification.

Here is my code:-

#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 );
}

This code notifies for a normal file correctly whenever the file gets modified. But, it doesn't work on device file, whenever there are changes in corresponding device mount directory. Is there anything wrong with my approach? Shouldn't /dev/sdX file get modified dynamically, whenever file system mounted on it gets changed?

I found a similar question Get notified about the change in raw data in hard disk sector - File change notification , but there were no useful answers on it.

Upvotes: 1

Views: 1542

Answers (1)

user149341
user149341

Reputation:

/dev/sda1 is a block device, not a regular file. inotify cannot observe devices for modifications. (Consider what this would even mean for other types of devices, like /dev/random…)

If you want to watch for any change on a filesystem, use fanotify instead.

Upvotes: 3

Related Questions