确保系统安装libinotify-dev
开发库:
sudo apt-get update
sudo apt-get install libinotify-dev
inotify_init()
初始化inotify实例,返回文件描述符(FD)。
int fd = inotify_init();
if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); }
inotify_add_watch(int fd, const char *path, uint32_t mask)
添加监控路径及事件类型(如IN_CREATE
、IN_DELETE
、IN_MODIFY
)。
int wd = inotify_add_watch(fd, "/path/to/dir", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); }
read(int fd, void *buf, size_t count)
读取事件缓冲区,解析struct inotify_event
结构体获取事件详情。
char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) { perror("read"); close(fd); exit(EXIT_FAILURE); }
inotify_rm_watch(int fd, int wd)
移除指定监控描述符(WD)。
inotify_rm_watch(fd, wd);
close(int fd)
关闭inotify实例。
close(fd);
以下程序监控指定目录的文件创建、删除、修改事件:
#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) {
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
// 1. 初始化inotify
int fd = inotify_init();
if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); }
// 2. 添加监控(目录、事件类型)
int wd = inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); }
// 3. 事件循环读取
char buffer[BUF_LEN];
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) { perror("read"); break; }
struct inotify_event *event;
for (char *ptr = buffer; ptr < buffer + length; ) {
event = (struct inotify_event *)ptr;
if (event->len) {
if (event->mask & IN_CREATE) {
printf("Created: %s\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("Deleted: %s\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("Modified: %s\n", event->name);
}
}
ptr += EVENT_SIZE + event->len;
}
}
// 4. 清理资源
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
gcc -o inotify_example inotify_example.c -linotify
./inotify_example /path/to/monitor
/proc/sys/fs/inotify/max_user_watches
查看/修改最大监控数量。cookie
字段区分事件序列。inotifywait
/inotifywatch
(属于inotify-tools
包)可快速测试监控:sudo apt-get install inotify-tools
inotifywait -m -e create,delete /path/to/dir
参考资料: