debian

Debian中inotify的API使用指南

小樊
46
2025-09-05 09:20:46
栏目: 智能运维

Debian中inotify API使用指南

一、安装依赖库

确保系统安装libinotify-dev开发库:

sudo apt-get update
sudo apt-get install libinotify-dev

二、核心API函数

  1. inotify_init()
    初始化inotify实例,返回文件描述符(FD)。

    int fd = inotify_init();
    if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); }
    
  2. inotify_add_watch(int fd, const char *path, uint32_t mask)
    添加监控路径及事件类型(如IN_CREATEIN_DELETEIN_MODIFY)。

    int wd = inotify_add_watch(fd, "/path/to/dir", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); }
    
  3. read(int fd, void *buf, size_t count)
    读取事件缓冲区,解析struct inotify_event结构体获取事件详情。

    char buffer[4096];
    ssize_t length = read(fd, buffer, sizeof(buffer));
    if (length < 0) { perror("read"); close(fd); exit(EXIT_FAILURE); }
    
  4. inotify_rm_watch(int fd, int wd)
    移除指定监控描述符(WD)。

    inotify_rm_watch(fd, wd);
    
  5. close(int fd)
    关闭inotify实例。

    close(fd);
    

三、完整代码示例

以下程序监控指定目录的文件创建、删除、修改事件:

#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) {
    if (argc != 2) {
        printf("Usage: %s <directory>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 1. 初始化inotify
    int fd = inotify_init();
    if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); }

    // 2. 添加监控(目录、事件类型)
    int wd = inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); }

    // 3. 事件循环读取
    char buffer[BUF_LEN];
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) { perror("read"); break; }

        struct inotify_event *event;
        for (char *ptr = buffer; ptr < buffer + length; ) {
            event = (struct inotify_event *)ptr;
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("Created: %s\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("Deleted: %s\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("Modified: %s\n", event->name);
                }
            }
            ptr += EVENT_SIZE + event->len;
        }
    }

    // 4. 清理资源
    inotify_rm_watch(fd, wd);
    close(fd);
    return 0;
}

四、编译与运行

  1. 编译代码:
    gcc -o inotify_example inotify_example.c -linotify
    
  2. 运行程序(指定监控目录):
    ./inotify_example /path/to/monitor
    

五、注意事项

六、扩展工具

参考资料:

0
看了该问题的人还看了