我正在使用 inotify 来监控本地文件,例如使用“/root/temp”
inotify_add_watch(fd, "/root/temp", mask).
当这个文件被删除时,程序会被read(fd, buf, bufSize)
函数阻塞。即使我创建了一个新的“/root/temp”文件,该程序仍然被读取功能阻塞。我想知道 inotify 是否可以检测到被监视的文件已创建,并且 read 函数可以从 fd 中获取一些东西,这样 read 就不会永远被阻塞。
这是我的代码:
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...
}
注意:未经测试的代码。
关于c++ - 使用 inotify 监控文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4664975/