inotify 是 Linux 内核提供的一种文件系统事件监控机制,它允许应用程序实时监控文件系统中的变化,如文件的创建、删除、修改等。inotify 提供了一系列的 API 接口,以下是一些主要的 API 接口:
inotify_init()inotify 实例,返回一个文件描述符。inotify_init1(int flags)inotify_init() 类似,但提供了更多的初始化选项。flags:可以设置为 IN_NONBLOCK(非阻塞模式)等。inotify_add_watch(int fd, const char *path, uint32_t mask)inotify 实例添加一个监控项。fd:inotify_init() 或 inotify_init1() 返回的文件描述符。path:要监控的文件或目录的路径。mask:监控事件的掩码,如 IN_CREATE、IN_DELETE、IN_MODIFY 等。read(int fd, struct inotify_event *event, size_t len)inotify 文件描述符读取事件。fd:inotify 文件描述符。event:指向 inotify_event 结构的指针,用于存储读取的事件。len:读取的最大字节数。inotify_rm_watch(int fd, int wd)fd:inotify 文件描述符。wd:要移除的监控项的 ID。close(int fd)inotify 文件描述符。fd:要关闭的文件描述符。inotify_event 结构inotify_event 结构用于存储读取的事件信息,定义如下:
struct inotify_event {
int wd; /* Watch descriptor */
uint32_t mask; /* Mask describing event */
uint32_t cookie; /* Unique cookie associating related events (for rename(2)) */
uint32_t len; /* Size of name field */
char name[]; /* Optional null-terminated name */
};
wd:监控项的 ID。mask:事件的掩码,表示发生了哪些事件。cookie:用于关联相关事件的唯一 cookie(例如在重命名事件中)。len:文件名的长度。name:可选的空终止文件名。以下是一个简单的示例代码,演示如何使用 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];
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
}
wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
}
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
}
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);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
return 0;
}
请根据实际需求调整代码中的路径和其他参数。