linux

inotify有哪些API接口可以使用

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

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

1. inotify_init()

2. inotify_init1(int flags)

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

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

5. inotify_rm_watch(int fd, int wd)

6. close(int fd)

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 */
};

示例代码

以下是一个简单的示例代码,演示如何使用 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
看了该问题的人还看了