ubuntu

Ubuntu inotify如何处理事件

小樊
40
2025-07-21 22:23:08
栏目: 智能运维

在Ubuntu中,inotify(Linux内核子系统)用于监控文件系统事件,例如文件或目录的创建、修改、删除等。要使用inotify处理这些事件,你需要使用Linux的inotify API。以下是一个简单的示例,说明如何使用inotify API处理文件系统事件:

  1. 首先,确保你的系统已经安装了inotify-tools。如果没有,请使用以下命令安装:
sudo apt-get install inotify-tools
  1. 创建一个名为inotify_example.c的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>\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_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    // 读取inotify事件
    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 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;
    }

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

    exit(EXIT_SUCCESS);
}
  1. 编译C文件:
gcc inotify_example.c -o inotify_example
  1. 运行程序,监控指定目录:
./inotify_example /path/to/directory

这个示例程序将监控指定的目录,并在文件或目录被创建、修改或删除时输出相应的消息。你可以根据需要修改事件掩码(event->mask)以监控其他事件。

0
看了该问题的人还看了