简体   繁体   English

使用inotify监控文件

[英]Monitoring file using inotify

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. 删除此文件时,将通过read(fd, buf, bufSize)函数阻止该程序。 Even if I create a new "/root/temp" file, the program is still block by read function. 即使我创建了一个新的“/ root / temp”文件,程序仍然被读取函数阻塞。 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. 我想知道inotify是否可以检测到已创建受监视文件,并且读取函数可以从fd获取某些内容,以便不会永久阻止读取。 Here is my code: 这是我的代码:

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. 我监控了所有事件。

The problem is that read is a blocking operation by default. 问题是默认情况下read是一个阻塞操作。

If you don't want it to block, use select or poll before read . 如果您不希望它阻止,请在read前使用selectpoll For example: 例如:

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. 注意 :未经测试的代码。

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_CREATE |的目录 IN_MOVED_TO to see newly created files (or files moved in from another place). IN_MOVED_TO用于查看新创建的文件(或从其他位置移入的文件)。

Some editors and other tools (eg rsync) may create a file under a different name, then rename it. 某些编辑器和其他工具(例如rsync)可能会以不同的名称创建文件,然后重命名它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM