inotify
是 Linux 内核提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。inotify
主要通过以下几个系统调用和 API 来使用:
inotify
提供了以下几个主要的系统调用:
inotify_init()
: 初始化一个 inotify 实例,返回一个文件描述符。inotify_add_watch()
: 添加一个监控项,指定要监控的文件或目录以及感兴趣的事件。read()
: 读取 inotify 事件。inotify_rm_watch()
: 移除一个监控项。close()
: 关闭 inotify 文件描述符。以下是一个简单的示例,演示如何使用 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];
// 检查命令行参数
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
// 初始化 inotify
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
// 添加监控项
wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
printf("Monitoring directory: %s\n", argv[1]);
// 读取事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
exit(EXIT_FAILURE);
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created.\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 关闭 inotify 文件描述符
close(fd);
return 0;
}
使用 gcc
编译上述代码:
gcc -o inotify_example inotify_example.c
然后运行程序并监控一个目录:
./inotify_example /path/to/directory
inotify
有监控数量的限制,可以通过 /proc/sys/fs/inotify/max_user_watches
文件查看和修改。inotify
事件可能会被合并,因此需要仔细处理事件的顺序和完整性。通过这些步骤,你可以使用 inotify
在 Linux 中监控文件系统的变化。