inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来检测文件的创建、修改、删除等操作。以下是使用 inotify 实现文件变更通知的基本步骤:
首先,确保你的系统上安装了 libinotify 库。在大多数 Linux 发行版中,这个库是默认安装的。如果没有安装,可以使用包管理器进行安装:
sudo apt-get install libinotify-dev # Debian/Ubuntu
sudo yum install libinotify-devel # CentOS/RHEL
下面是一个使用 libinotify 库的简单示例代码,用于监控指定目录下的文件变更:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
void print_event( struct inotify_event *event ) {
printf( "Event type: %d\n", event->mask );
if ( event->mask & IN_CREATE ) {
printf( "File created: %s\n", event->name );
}
if ( event->mask & IN_DELETE ) {
printf( "File deleted: %s\n", event->name );
}
if ( event->mask & IN_MODIFY ) {
printf( "File modified: %s\n", event->name );
}
if ( event->mask & IN_MOVED_FROM ) {
printf( "File moved from: %s\n", event->name );
}
if ( event->mask & IN_MOVED_TO ) {
printf( "File moved to: %s\n", event->name );
}
}
int main( int argc, char **argv ) {
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
// 检查命令行参数
if ( argc < 2 ) {
printf( "Usage: %s <directory>\n", argv[0] );
exit( 1 );
}
// 创建 inotify 实例
fd = inotify_init();
if ( fd < 0 ) {
perror( "inotify_init" );
exit( 1 );
}
// 添加监控目录
wd = inotify_add_watch( fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO );
if ( wd < 0 ) {
perror( "inotify_add_watch" );
exit( 1 );
}
printf( "Monitoring directory: %s\n", argv[1] );
while ( 1 ) {
length = read( fd, buffer, BUF_LEN );
if ( length < 0 ) {
perror( "read" );
exit( 1 );
}
while ( i < length ) {
struct inotify_event *event = ( struct inotify_event *)&buffer[i];
print_event( event );
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控并关闭 inotify 实例
inotify_rm_watch( fd, wd );
close( fd );
return 0;
}
使用 gcc 编译上述代码:
gcc -o inotify_example inotify_example.c -linotify
运行编译后的程序,并指定要监控的目录:
./inotify_example /path/to/directory
inotify_init():初始化 inotify 实例,返回文件描述符。inotify_add_watch():添加监控目录,返回监控描述符(watch descriptor)。read():读取 inotify 事件。print_event():解析并打印事件信息。通过上述步骤,你可以使用 inotify 实现对文件变更的实时通知。