c - 如何在 C 中使用 inotify?

标签 c inotify

我搜索了inotify相关的问题,这个有点不一样...

我使用以下代码来监视一个文件(不是目录)的更改。在测试中,当我保存目标文件时 read() 确实返回,这意味着它可以工作。但是 event->mask 是 32768,它不是 IN_MODIFY 并且 name 是空的。另一个问题:它不能持续监控。当我第二次更改文件时,它没有任何反应。感谢您的帮助!

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

#define EVENT_SIZE  (sizeof (struct inotify_event))
#define BUF_LEN        (16 * (EVENT_SIZE + 16))

int main()
{
    int fd;
    fd = inotify_init();
    if (fd < 0)
        perror("inotify_init()");

    int wd;
    wd = inotify_add_watch(fd, "target.txt", IN_MODIFY);
    if (wd < 0)
        perror("inotify_add_watch");

    char buf[BUF_LEN];
    int len;

start:

    len = read(fd, buf, BUF_LEN);

    if (len > 0)
    {
        int i = 0;
        while (i < len)
        {
            struct inotify_event *event;
            event = (struct inotify_event *) &buf[i];

            printf("wd=%d mask=%x cookie=%u len=%u\n",
                event->wd, event->mask,
                event->cookie, event->len);

            if (event->mask & IN_MODIFY)
                printf("file modified %s", event->name);

            if (event->len)
                printf("name=%s\n", event->name);

            i += EVENT_SIZE + event->len;
        }
    }

    goto start;

    return 0;
}

最佳答案

0x8000 对应于 IN_IGNORED。它在掩码中的存在表明 inotify 监视已被删除,因为该文件已被删除。您的编辑器可能删除了旧文件并在其位置放置了一个新文件。第二次更改文件没有效果,因为 watch 已被删除。

名称未返回,因为您未查看目录。

来自inotify man page .

The name field is only present when an event is returned for a file inside a watched directory; it identifies the file pathname relative to the watched directory.

...

IN_IGNORED -- Watch was removed explicitly (inotify_rm_watch(2)) or automatically (file was deleted, or file system was unmounted).

关于c - 如何在 C 中使用 inotify?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15350369/

相关文章:

lua - 我如何在 lua 中 tail -F 一个日志文件(截断感知)?

c - 从 inotify_event 中检索完整路径名

c++ - MPI calloc 导致段错误

c - 从输入文件中读取数据并将其存储到结构数组中

html - 如何将 Grep 实现到 CGI 脚本中?

java - Collat​​z 和其他序列 : how to get more precision easily and avoid segfault?

c - 在 Linux 中保护文件不被编辑

python - pyinotify 疑似线程问题

c++ - MacOS - 如何使用 C/C++ 获取具有 PID 的进程用户/所有者?

virtualbox - 使用 boot2docker 从主机共享代码目录不会在 guest 上调用 inotify