linux

inotify的API接口有哪些

小樊
53
2025-10-01 16:26:52
栏目: 编程语言

inotify 是 Linux 内核提供的一种文件系统事件监控机制,它允许应用程序实时监控文件系统对象(如文件、目录)的变化,包括创建、删除、修改等操作。inotify 提供了几个主要的 API 接口,以下是一些常用的:

1. inotify_init()

2. inotify_add_watch()

3. read()

4. inotify_rm_watch()

5. close()

事件掩码(mask)

inotify 使用事件掩码来指定要监控的事件类型。常见的事件类型包括:

示例代码

以下是一个简单的示例代码,演示如何使用 inotify 监控一个目录:

#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, "/path/to/directory", IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        return 1;
    }

    // 读取事件
    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 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_rm_watch(fd, wd);
    close(fd);

    return 0;
}

这个示例代码展示了如何初始化 inotify,添加监控项,读取事件,并在检测到文件变化时打印相应的消息。

0
看了该问题的人还看了