![](/img/trans.png)
[英]inotify stops monitoring file when the file is deleted and created again
[英]Monitoring file using inotify
我使用inotify监视本地文件,例如“/ root / temp”使用
inotify_add_watch(fd, "/root/temp", mask).
删除此文件时,将通过read(fd, buf, bufSize)
函数阻止该程序。 即使我创建了一个新的“/ root / temp”文件,程序仍然被读取函数阻塞。 我想知道inotify是否可以检测到已创建受监视文件,并且读取函数可以从fd获取某些内容,以便不会永久阻止读取。 这是我的代码:
uint32_t mask = IN_ALL_EVENTS;
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", mask);
char *buf = new char[1000];
int nbytes = read(fd, buf, 500);
我监控了所有事件。
问题是默认情况下read
是一个阻塞操作。
如果您不希望它阻止,请在read
前使用select
或poll
。 例如:
struct pollfd pfd = { fd, POLLIN, 0 };
int ret = poll(&pfd, 1, 50); // timeout of 50ms
if (ret < 0) {
fprintf(stderr, "poll failed: %s\n", strerror(errno));
} else if (ret == 0) {
// Timeout with no events, move on.
} else {
// Process the new event.
struct inotify_event event;
int nbytes = read(fd, &event, sizeof(event));
// Do what you need...
}
注意 :未经测试的代码。
要查看创建的新文件,您需要查看目录,而不是文件。 观察文件时应该看到它被删除(IN_DELETE_SELF),但是如果创建了一个具有相同名称的新文件,则可能无法看到该文件。
你应该看一下IN_CREATE |的目录 IN_MOVED_TO用于查看新创建的文件(或从其他位置移入的文件)。
某些编辑器和其他工具(例如rsync)可能会以不同的名称创建文件,然后重命名它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.