inotify
是 Linux 系统中用于监控文件系统事件的机制。要设置 inotify
的事件掩码,您需要使用 inotify_init
或 inotify_init1
函数创建一个 inotify
实例,然后使用 inotify_add_watch
函数为该实例添加监控目录,并指定所需的事件掩码。
以下是一个简单的示例,演示如何使用 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;
}
// 添加监控目录,设置事件掩码为 IN_CREATE | IN_DELETE
wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
return 1;
}
// 读取 inotify 事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
return 1;
}
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);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控并关闭 inotify 实例
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
在这个示例中,我们使用 inotify_add_watch
函数添加了一个监控目录,并设置了事件掩码为 IN_CREATE | IN_DELETE
,这意味着我们将监控目录中的文件创建和删除事件。事件掩码可以包含多个事件,例如 IN_MODIFY
(文件修改)、IN_ATTRIB
(文件属性更改)等。您可以参考 inotify
的手册页(man 7 inotify
)以获取完整的事件列表。
请注意,这个示例仅用于演示目的,实际应用中可能需要处理更多的错误情况和边界条件。