温馨提示×

inotify有哪些API接口可以使用

小樊
33
2025-12-10 12:28:57
栏目: 编程语言

inotify 是 Linux 内核提供的一种文件系统事件监控机制,它允许应用程序实时监控文件系统中的变化,如文件的创建、删除、修改等。inotify 提供了一系列的 API 接口,以下是一些主要的 API 接口:

1. inotify_init()

  • 功能:初始化一个 inotify 实例,返回一个文件描述符。
  • 返回值:成功时返回文件描述符,失败时返回 -1。

2. inotify_init1(int flags)

  • 功能:与 inotify_init() 类似,但提供了更多的初始化选项。
  • 参数
    • flags:可以设置为 IN_NONBLOCK(非阻塞模式)等。
  • 返回值:成功时返回文件描述符,失败时返回 -1。

3. inotify_add_watch(int fd, const char *path, uint32_t mask)

  • 功能:向 inotify 实例添加一个监控项。
  • 参数
    • fdinotify_init()inotify_init1() 返回的文件描述符。
    • path:要监控的文件或目录的路径。
    • mask:监控事件的掩码,如 IN_CREATEIN_DELETEIN_MODIFY 等。
  • 返回值:成功时返回监控项的 ID,失败时返回 -1。

4. read(int fd, struct inotify_event *event, size_t len)

  • 功能:从 inotify 文件描述符读取事件。
  • 参数
    • fdinotify 文件描述符。
    • event:指向 inotify_event 结构的指针,用于存储读取的事件。
    • len:读取的最大字节数。
  • 返回值:成功时返回读取的事件数量,失败时返回 -1。

5. inotify_rm_watch(int fd, int wd)

  • 功能:移除一个监控项。
  • 参数
    • fdinotify 文件描述符。
    • wd:要移除的监控项的 ID。
  • 返回值:成功时返回 0,失败时返回 -1。

6. close(int fd)

  • 功能:关闭 inotify 文件描述符。
  • 参数
    • fd:要关闭的文件描述符。
  • 返回值:成功时返回 0,失败时返回 -1。

inotify_event 结构

inotify_event 结构用于存储读取的事件信息,定义如下:

struct inotify_event {
    int wd;             /* Watch descriptor */
    uint32_t mask;      /* Mask describing event */
    uint32_t cookie;    /* Unique cookie associating related events (for rename(2)) */
    uint32_t len;       /* Size of name field */
    char name[];        /* Optional null-terminated name */
};
  • wd:监控项的 ID。
  • mask:事件的掩码,表示发生了哪些事件。
  • cookie:用于关联相关事件的唯一 cookie(例如在重命名事件中)。
  • len:文件名的长度。
  • name:可选的空终止文件名。

示例代码

以下是一个简单的示例代码,演示如何使用 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];

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

    return 0;
}

请根据实际需求调整代码中的路径和其他参数。

0