在Linux中,inotify是一个用于监控文件系统事件的API。使用inotify可以检测文件的创建、删除、修改等事件。以下是使用inotify检测文件修改的基本步骤:
首先,确保你的系统上安装了libinotify库。大多数Linux发行版默认已经安装了这个库。
下面是一个简单的C语言示例,演示如何使用inotify检测文件修改:
#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 ) )
int main(int argc, char **argv) {
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
// 创建inotify实例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
// 添加要监控的文件或目录
wd = inotify_add_watch(fd, "/path/to/your/file", IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
printf("Monitoring file for modifications...\n");
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
break;
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_MODIFY) {
printf("File %s was modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控并关闭文件描述符
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
使用gcc编译上述代码:
gcc -o inotify_example inotify_example.c
运行编译后的程序:
./inotify_example
程序将开始监控指定文件的修改事件,并在检测到文件修改时输出相应的消息。
inotify_init():创建一个新的inotify实例。inotify_add_watch():添加一个监控项,指定要监控的文件或目录以及感兴趣的事件(例如IN_MODIFY表示文件修改)。read():从inotify实例读取事件。inotify_rm_watch():移除监控项。close():关闭文件描述符。通过这种方式,你可以使用inotify来实时监控文件的修改事件。