c++ - 使用 inotify 监控文件

标签 c++ linux nonblocking file-descriptor inotify

我正在使用 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 之前使用selectpoll。例如:

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/

相关文章:

linux - sed 打印替换行两次

linux - 无法将存储库克隆到 linux 上的 jenkins

javascript - Node.js 是否同时只执行一个上下文?

sockets - 在不关闭连接的情况下关闭从 TCP 连接读取的 goroutine

Ruby readpartial 和 read_nonblock 不抛出 EOFError

c++ - 使用 C++,使用 QWebView 显示 HTML 文本,而不是网络上某处的网页

c++ - 指向类的指针和指向方法的指针

c++ - C++程序优化

c++ - 在 C++ 中实践什么用于字节操作 uint8 或 char?

linux - 如何在树莓派的主目录中创建文件夹?