debian

Debian inotify使用教程是什么

小樊
34
2025-09-13 09:59:48
栏目: 智能运维

Debian inotify 使用教程

一、安装工具

通过 apt 安装 inotify-tools(含命令行工具):

sudo apt update  
sudo apt install inotify-tools libinotify-dev  # 后者用于编程开发  

二、命令行工具使用

1. inotifywait(实时监控)
2. inotifywatch(事件统计)

三、编程接口使用(libinotify)

需安装开发包 libinotify-dev,通过代码实现监控逻辑(以 C 语言为例):

  1. 安装开发包
    sudo apt install libinotify-dev  
    
  2. 示例代码:监控当前目录的创建、修改事件:
    #include <stdio.h>  
    #include <sys/inotify.h>  
    #define EVENT_SIZE  (sizeof(struct inotify_event))  
    #define BUF_LEN     (1024 * (EVENT_SIZE + 16))  
    
    int main() {  
        int fd = inotify_init();  
        if (fd < 0) { perror("inotify_init"); return 1; }  
    
        int wd = inotify_add_watch(fd, ".", IN_CREATE | IN_MODIFY);  
        if (wd < 0) { perror("inotify_add_watch"); return 1; }  
    
        char buffer[BUF_LEN];  
        read(fd, buffer, BUF_LEN);  // 读取事件数据  
    
        // 解析事件  
        struct inotify_event *event = (struct inotify_event *)buffer;  
        if (event->mask & IN_CREATE) printf("File created: %s\n", event->name);  
        if (event->mask & IN_MODIFY) printf("File modified: %s\n", event->name);  
    
        inotify_rm_watch(fd, wd);  
        close(fd);  
        return 0;  
    }  
    
  3. 编译运行
    gcc -o inotify_example inotify_example.c -linotify  
    ./inotify_example  
    

四、高级用法

注意事项

参考资料:

0
看了该问题的人还看了