【发布时间】: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