9

我正在使用 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);

我监视了所有事件。

4

2 回答 2

22

问题是read默认情况下这是一个阻塞操作。

如果您不希望它阻止,请使用selector pollbefore read。例如:

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...
}

注意:未经测试的代码。

于 2011-01-12T03:07:26.577 回答
3

为了查看创建的新文件,您需要查看目录,而不是文件。观察文件应该会看到它何时被删除(IN_DELETE_SELF),但如果创建了同名的新文件,则可能不会发现。

您可能应该注意 IN_CREATE | 的目录。IN_MOVED_TO 查看新创建的文件(或从其他地方移入的文件)。

一些编辑器和其他工具(例如 rsync)可能会以不同的名称创建文件,然后重命名它。

于 2011-01-12T08:04:46.080 回答