c - 使用C语言的Inotify在我的目录中持续监控
问题描述
我试图在我的目录中持续监视以了解何时使用 C 语言中的 Inotify 创建、删除、修改文件。
我做了如下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.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, ".",
IN_MODIFY | IN_CREATE | IN_DELETE);
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("The file %s was created.\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("The file %s was deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("The file %s was modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
return 0;
}
但是在这里创建一个新文件后,它会立即出现,但我正在尝试不断观察我的目录中发生的事情。
解决方案
推荐阅读
- python - OSError: [Errno 26] 文本文件忙
- realm - 如何让keycloak导出领域用户然后退出
- gatsby - 内容小数
- php - 使用 facebook-graph-api 从 facebook 上的一位用户获取所有事件
- c++ - 为什么 QT 告诉我我的 QDialog 继承类不是 QWidget?
- java - Mockito 中的类型安全问题 - 模拟集合
- ios - 使用 SwiftUI 实现 Apple Pay
- kotlin - 为什么带有 newSingleThreadExecutor 的 runBlocking 块不结束?
- python - 让python等待通过tkinter设置变量
- angular - Angular Jasmine 单元测试 NullInjectorError: R3InjectorError(CompilerModule)[CheckForUpdateService -> CheckForUpdateService]: