c - inotify 真的适用于文件还是仅适用于目录?

标签 c linux inotify

我正在尝试使用 inotify 来监视对文件 /dev/hvc0 的更改,方法如下:

#include <stdio.h>
#include <sys/inotify.h>
#include <stdlib.h>

#define EVENT_SIZE  (sizeof(struct inotify_event))
#define BUF_LEN     (1024 * (EVENT_SIZE + 16))
#define WATCH_FILE "/dev/hvc0" /* This file should be present
                                  before this program is run */

int main() {
    int notify_fd;
    int length;
    int i = 0;
    char buffer[BUF_LEN];
    notify_fd = inotify_init();
    if (notify_fd < 0) {
        perror("inotify_init");
    }
    int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS);
    int length_read = read(notify_fd, buffer, BUF_LEN);
    if (length_read) {
        perror("read");
    }
    while (i < length_read) {
        struct inotify_event *event =
            (struct inotify_event *) &buffer[i];
        if (event->len) {
            if (event->mask & IN_ACCESS) {
                printf("The file %s was accessed.\n", event->name);
            } else if (event->mask & IN_MODIFY) {
                printf("The file %s was modified.\n", event->name);
            }
        }
    }

    (void) inotify_rm_watch(notify_fd, wd);
    (void) close(notify_fd);
    return 0;
}

但是,如果文件被访问/修改,则不会打印。但是,每当我将要监视的路径更改为目录并且更改了文件时,它都会打印出发生的正确事件。

inotify 是否也适用于监控文件更改?还是我做错了什么?

谢谢!

最佳答案

您缺少增加 i 。在循环结束之前添加:

i += EVENT_SIZE + event->len;

如果要监控变化,还需要将读取/打印操作包装在无限循环中。

关于c - inotify 真的适用于文件还是仅适用于目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646092/

相关文章:

安装 Yii 2 框架后 Web basic 上的 PHP 核心警告

python - pyinotify 疑似线程问题

Perl Linux::Inotify2 - 无法再响应事件

c - 如何在 Linux/C 中获得更稳定的套接字连接

linux - 使用此处文档时将 bash 输出写入文件

c - 使用多维数组 C 求 5 个学生的平均值

c - 在 c system() 之前执行 printf() 即使 printf 先出现

c - 是否有任何 POSIX 函数或 glibc 扩展实现了广度优先文件树遍历?

c - 使用读写锁在 pthreads 哈希表中读取性能不佳

c - 如何枚举 USB 设备*和*读取/写入它们?