linux

inotify在Linux下如何配置使用

小樊
46
2025-07-27 17:32:47
栏目: 智能运维

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。要配置和使用 inotify,你可以使用多种工具和库,其中最常用的是 inotify-toolslibinotify

使用 inotify-tools

inotify-tools 是一个简单的命令行工具集,用于监控文件系统事件。首先,你需要安装它:

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

安装完成后,你可以使用 inotifywaitinotifywatch 命令来监控文件系统。

inotifywait

inotifywait 命令用于等待指定的文件或目录发生事件。基本用法如下:

inotifywait [选项] 目标文件或目录

常用选项:

示例:

inotifywait -m -r -e create,delete,modify /path/to/directory

inotifywatch

inotifywatch 命令用于统计文件系统事件的发生次数。基本用法如下:

inotifywatch [选项] 监控时间 目标文件或目录

常用选项:

示例:

inotifywatch -t 60 -r -e create,delete,modify /path/to/directory

使用 libinotify

libinotify 是一个 C 语言库,用于在程序中集成 inotify 功能。首先,你需要安装它:

sudo apt-get install libinotify-dev  # Debian/Ubuntu
sudo yum install libinotify-devel      # CentOS/RHEL

安装完成后,你可以在 C 程序中使用 libinotify 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];

    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
    }

    wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) {
        perror("inotify_add_watch");
    }

    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);
            }
            if (event->mask & IN_DELETE) {
                printf("File %s was deleted.\n", event->name);
            }
            if (event->mask & IN_MODIFY) {
                printf("File %s was modified.\n", event->name);
            }
        }
        i += EVENT_SIZE + event->len;
    }

    (void) inotify_rm_watch(fd, wd);
    (void) close(fd);

    exit(0);
}

编译并运行这个程序:

gcc -o inotify_example inotify_example.c
./inotify_example

这个示例程序会监控指定目录,并在文件创建、删除或修改时打印相应的消息。

通过这些工具和库,你可以在 Linux 系统中灵活地配置和使用 inotify 来监控文件系统事件。

0
看了该问题的人还看了