linux

如何用inotify实现实时监控

小樊
40
2025-07-05 12:36:52
栏目: 编程语言

inotify 是 Linux 系统提供的一种文件系统事件监控机制,可以用来实时监控文件或目录的变化。以下是使用 inotify 实现实时监控的基本步骤:

1. 安装必要的库

在大多数 Linux 发行版中,inotify 工具和库已经预装。如果没有,可以使用包管理器进行安装。

sudo apt-get install inotify-tools  # Debian/Ubuntu
sudo yum install inotify-tools      # CentOS/RHEL

2. 使用 inotifywait 命令

inotifywait 是一个命令行工具,可以用来监控文件或目录的变化。

监控单个文件

inotifywait -m /path/to/file -e modify,attrib,close_write,move,create,delete

监控整个目录

inotifywait -m /path/to/directory -e modify,attrib,close_write,move,create,delete

3. 使用 inotify API 编程

如果你需要在自己的应用程序中实现实时监控,可以使用 inotify API。

示例代码(C语言)

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

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

int main(int argc, char **argv) {
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN];

    // 创建 inotify 实例
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
    }

    // 添加监控目录
    wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVE | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
    }

    // 监控事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("File %s was created.\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s was deleted.\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s was modified.\n", event->name);
                } else if (event->mask & IN_ATTRIB) {
                    printf("File %s attributes were changed.\n", event->name);
                } else if (event->mask & IN_CLOSE_WRITE) {
                    printf("File %s was closed after being written to.\n", event->name);
                } else if (event->mask & IN_MOVE) {
                    printf("File %s was moved.\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除监控并关闭 inotify 实例
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

4. 处理事件

在监控过程中,你可以根据不同的事件类型执行相应的操作。例如,当检测到文件创建时,可以自动备份文件;当检测到文件删除时,可以记录日志等。

5. 注意事项

通过以上步骤,你可以使用 inotify 实现对文件或目录的实时监控。

0
看了该问题的人还看了