inotify是否真正适用于文件或仅适用于目录?

问题描述 投票:1回答:3

我正在尝试使用以下命令使用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是否也可用于监视文件更改?还是我做错了?

谢谢!

c linux inotify
3个回答
0
投票

我不明白为什么event->len返回零,可能是因为未返回文件名。但仅出于测试目的,您只需对其进行评论。第二点您对i的处理已损坏,您永远不会在循环中将其重置为0。这使得仅在它们比之前的最长事件长时才考虑后期的inotin事件,这不太可能是您想要的。并且请在while循环中,请输入i += EVENT_SIZE + event->len;


1
投票

您缺少增加i的功能。在循环结束前添加它:


0
投票

根据此answer,看来Linux无法监视特定文件。如果要听特定的文件,则应先听其父目录。

© www.soinside.com 2019 - 2024. All rights reserved.