linux

inotify如何与脚本结合

小樊
46
2025-09-21 01:27:35
栏目: 编程语言

inotify 是 Linux 系统中的一个功能,用于监控文件系统事件,如文件或目录的创建、修改、删除等。你可以使用 inotifywait 命令或编写自己的程序来使用 inotify API。下面是如何将 inotify 与脚本结合的一些示例。

使用 inotifywait 命令

inotifywaitinotify-tools 包的一部分,它提供了一个简单的命令行界面来使用 inotify。首先,确保你已经安装了 inotify-tools

sudo apt-get install inotify-tools  # 对于基于 Debian 的系统
sudo yum install inotify-tools      # 对于基于 RHEL 的系统

然后,你可以编写一个简单的脚本来监控文件或目录的变化。例如,以下脚本会在检测到 /path/to/directory 目录中的任何更改时打印一条消息:

#!/bin/bash

DIRECTORY_TO_WATCH="/path/to/directory"

inotifywait -m -r -e create,modify,delete --format '%w%f %e' "$DIRECTORY_TO_WATCH" | while read FILE EVENT
do
    echo "The file '$FILE' appeared in directory '$DIRECTORY_TO_WATCH' via event '$EVENT'"
done

在这个脚本中:

使用 inotify API 编写脚本

如果你需要更复杂的逻辑或者更好的性能,你可以使用 inotify 的 C 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];

    // 检查命令行参数
    if (argc != 2) {
        printf("Usage: %s <directory_to_watch>\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_CREATE | IN_DELETE | IN_MODIFY);
    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 实例
    (void) inotify_rm_watch(fd, wd);
    (void) close(fd);

    exit(EXIT_SUCCESS);
}

编译这个程序:

gcc -o inotify_example inotify_example.c

运行程序并监控一个目录:

./inotify_example /path/to/directory

这个 C 程序会持续运行并监控指定的目录,当检测到文件创建、删除或修改时,它会打印相应的消息。

根据你的需求,你可以选择使用 inotifywait 命令行工具或者编写自己的程序来使用 inotify API。记得处理好错误和异常情况,以确保脚本或程序的稳定性。

0
看了该问题的人还看了