linux

如何用inotify实现文件监控

小樊
49
2025-08-15 14:39:09
栏目: 编程语言

inotify 是 Linux 系统提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。以下是使用 inotify 实现文件监控的基本步骤:

1. 安装必要的库

在大多数 Linux 发行版中,inotify 工具和库已经预装。如果没有,可以使用包管理器进行安装。例如,在 Debian/Ubuntu 上:

sudo apt-get install inotify-tools libinotify-dev

2. 编写代码

下面是一个使用 C 语言和 libinotify 库的简单示例,展示如何监控一个目录中的文件变化。

安装 libinotify 开发包

sudo apt-get install libinotify-dev

示例代码

#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 ) )

void monitor_directory(const char *path) {
    int length, i = 0;
    int fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return;
    }

    int wd = inotify_add_watch(fd, path, IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        return;
    }

    char buffer[BUF_LEN];

    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            break;
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("File %s created\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s deleted\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s modified\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

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

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    monitor_directory(argv[1]);

    return EXIT_SUCCESS;
}

编译代码

gcc -o monitor_directory monitor_directory.c -linotify

运行程序

./monitor_directory /path/to/directory

3. 解释代码

4. 其他语言的实现

如果你使用其他编程语言,如 Python,可以使用 pyinotify 库来实现类似的功能。

安装 pyinotify

pip install pyinotify

示例代码

import pyinotify

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_MODIFY(self, event):
        print(f"File {event.pathname} modified")

    def process_IN_CREATE(self, event):
        print(f"File {event.pathname} created")

    def process_IN_DELETE(self, event):
        print(f"File {event.pathname} deleted")

def monitor_directory(path):
    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_DELETE
    notifier = pyinotify.Notifier(wm, EventHandler())
    wm.add_watch(path, mask, rec=True)
    notifier.loop()

if __name__ == "__main__":
    monitor_directory("/path/to/directory")

通过这些步骤,你可以使用 inotify 实现文件监控功能。根据你的需求,可以选择合适的编程语言和库来实现。

0
看了该问题的人还看了