温馨提示×

inotify的API如何调用

小樊
53
2025-09-12 17:18:12
栏目: 编程语言

inotify 是 Linux 内核提供的一种文件系统事件监控机制,允许应用程序实时监控文件系统中的变化,如文件的创建、删除、修改和移动等。inotify 的 API 主要包括以下几个部分:

  1. 初始化 inotify 实例: 使用 inotify_init()inotify_init1() 函数来创建一个新的 inotify 实例。

    #include <sys/inotify.h>
    
    int inotify_init(void);
    int inotify_init1(int flags);
    

    inotify_init1() 允许你通过 flags 参数指定一些选项,例如 IN_NONBLOCK

  2. 添加监控: 使用 inotify_add_watch() 函数来添加对特定文件或目录的监控。

    int inotify_add_watch(int fd, const char *path, uint32_t mask);
    
    • fdinotify_init() 返回的文件描述符。
    • path 是你想要监控的文件或目录的路径。
    • mask 是一个位掩码,指定了你想要监控的事件类型,例如 IN_MODIFY, IN_CREATE, IN_DELETE 等。
  3. 读取事件: 使用 read() 系统调用从 inotify 文件描述符中读取事件。

    ssize_t read(int fd, void *buf, size_t count);
    
    • fd 是 inotify 文件描述符。
    • buf 是一个缓冲区,用于存储读取的事件。
    • count 是缓冲区的大小。

    读取到的事件结构体是 struct inotify_event,它包含了事件的相关信息,如事件类型、文件名等。

  4. 移除监控: 使用 inotify_rm_watch() 函数来移除之前添加的监控。

    int inotify_rm_watch(int fd, int watch_descriptor);
    
    • fd 是 inotify 文件描述符。
    • watch_descriptor 是由 inotify_add_watch() 返回的监控描述符。
  5. 关闭 inotify 实例: 当不再需要监控时,使用 close() 系统调用关闭 inotify 文件描述符。

    int close(int fd);
    

下面是一个简单的示例,演示了如何使用 inotify API 来监控一个文件的变化:

#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];

    // 检查命令行参数
    if (argc != 2) {
        printf("Usage: %s <file or directory to monitor>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 初始化 inotify
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        exit(EXIT_FAILURE);
    }

    // 添加监控
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    // 读取事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        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);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

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

    return 0;
}

这个示例程序会监控命令行参数指定的文件或目录,并在检测到文件创建、删除或修改事件时打印相应的消息。请注意,这个程序是一个无限循环,它会一直运行直到被外部信号终止。在实际应用中,你可能需要添加适当的退出逻辑。

0