linux

inotify API如何使用

小樊
49
2025-08-21 16:02:12
栏目: 编程语言

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

  1. inotify_init(): 创建一个新的 inotify 实例并返回一个文件描述符。
  2. inotify_add_watch(): 添加一个监控项到 inotify 实例中,指定要监控的文件或目录以及感兴趣的事件。
  3. read(): 从 inotify 文件描述符中读取事件。
  4. inotify_rm_watch(): 移除一个监控项。
  5. close(): 关闭 inotify 文件描述符。

下面是一个简单的示例,展示如何使用 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];

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

    // 添加监控项,监控当前目录下的所有文件,感兴趣的事件包括创建、删除和修改
    wd = inotify_add_watch(fd, ".", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) {
        perror("inotify_add_watch");
        return 1;
    }

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

        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;
}

编译并运行这个程序,它将监控当前目录下的文件变化,并在控制台输出相应的事件信息。

请注意,inotify API 的使用可能会受到一些限制,例如单个进程可以监控的文件描述符数量、监控的文件数量等。在实际应用中,可能需要根据具体需求进行调整和优化。

0
看了该问题的人还看了