linux

inotify如何检测文件创建

小樊
42
2025-09-02 16:58:05
栏目: 编程语言

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来检测文件的创建、修改、删除等事件。要使用 inotify 检测文件创建,你可以使用 Linux 的 inotify-tools 工具集,或者直接使用 inotify API。

使用 inotify-tools

  1. 安装 inotify-tools

    在大多数 Linux 发行版中,你可以使用包管理器来安装 inotify-tools。例如,在基于 Debian 的系统上,可以使用以下命令:

    sudo apt-get install inotify-tools
    
  2. 使用 inotifywait 监控目录

    inotifywaitinotify-tools 中的一个命令行工具,可以用来监控文件系统事件。以下是一个简单的示例,用于监控当前目录下的文件创建事件:

    inotifywait -m -e create --format '%w%f' .
    

    解释:

    • -m:监控模式,持续监控而不是等待事件。
    • -e create:指定要监控的事件类型,这里是文件创建。
    • --format '%w%f':指定输出格式,%w 表示文件所在的目录,%f 表示文件名。
    • .:监控当前目录。

使用 inotify API

如果你需要在自己的程序中使用 inotify,可以使用 Linux 提供的 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");
        return 1;
    }

    // 添加监控目录
    wd = inotify_add_watch(fd, ".", IN_CREATE);
    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);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

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

    return 0;
}

编译并运行这个程序:

gcc -o inotify_example inotify_example.c
./inotify_example

这个程序会持续监控当前目录下的文件创建事件,并在检测到文件创建时打印文件名。

通过这两种方法,你可以使用 inotify 来检测文件的创建事件。

0
看了该问题的人还看了