Linux 使用 inotify 监控文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4664975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:26:30  来源:igfitidea点击:

Monitoring file using inotify

c++linuxnonblockingfile-descriptorinotify

提问by user572138

I am using inotify to monitor a local file, for example "/root/temp" using

我正在使用 inotify 来监视本地文件,例如“/root/temp”使用

inotify_add_watch(fd, "/root/temp", mask).

When this file is deleted, the program will be blocked by read(fd, buf, bufSize)function. Even if I create a new "/root/temp" file, the program is still block by read function. I am wondering if inotify can detect that the monitored file is created and the read function can get something from fd so that read will not be blocked forever. Here is my code:

当这个文件被删除时,程序将被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);

I monitored all events.

我监控了所有事件。

回答by jweyrich

The problem is that readis a blocking operation by default.

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

If you don't want it to block, use selector pollbefore read. For example:

如果您不想阻止它,请使用selectpollbefore 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...
}

Note: untested code.

注意:未经测试的代码。

回答by MarkR

In order to see a new file created, you need to watch the directory, not the file. Watching a file should see when it is deleted (IN_DELETE_SELF) but may not spot if a new file is created with the same name.

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

You should probably watch the directory for IN_CREATE | IN_MOVED_TO to see newly created files (or files moved in from another place).

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

Some editors and other tools (e.g. rsync) may create a file under a different name, then rename it.

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