inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。inotify 的 API 主要包括以下几个部分:
初始化 inotify 实例:
使用 inotify_init() 或 inotify_init1() 函数来创建一个 inotify 实例。inotify_init1() 提供了更多的选项,比如可以设置标志位。
int fd = inotify_init();
if (fd < 0) {
// 错误处理
}
添加监控:
使用 inotify_add_watch() 函数来添加对文件或目录的监控。你需要提供 inotify 文件描述符、要监控的文件或目录路径,以及你感兴趣的事件类型。
int wd = inotify_add_watch(fd, "/path/to/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
// 错误处理
}
这里的 wd 是一个唯一的监视描述符,用于后续的事件读取。
读取事件:
使用 read() 系统调用来读取 inotify 事件。事件会被存储在一个 inotify_event 结构体中。
char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
// 错误处理
}
// 解析 buffer 中的事件
inotify_event 结构体定义如下:
struct inotify_event {
int wd; /* watch descriptor */
uint32_t mask; /* mask of events */
uint32_t cookie; /* unique cookie associating related events (for rename(2)) */
uint32_t len; /* size of name field */
char name[]; /* optional null-terminated name */
};
mask 字段包含了发生的事件类型,例如 IN_MODIFY、IN_CREATE、IN_DELETE 等。
移除监控:
当不再需要监控某个文件或目录时,可以使用 inotify_rm_watch() 函数来移除监控。
int ret = inotify_rm_watch(fd, wd);
if (ret < 0) {
// 错误处理
}
关闭 inotify 实例:
当不再需要 inotify 实例时,应该使用 close() 系统调用来关闭它。
close(fd);
请注意,inotify API 的使用可能会受到一些限制,比如单个进程可以监控的文件描述符数量、监控的文件系统事件数量等。这些限制可以通过调整内核参数来改变。
此外,处理 inotify 事件时,需要注意缓冲区的大小可能不足以容纳所有的事件数据,因此可能需要循环读取直到没有更多的数据为止。同时,对于文件名字段(name[]),它是一个可变长度的字段,因此在解析时需要考虑到这一点。