在Debian系统下,要实时处理inotify事件,你可以使用inotify-tools或libinotify库。这里将分别介绍这两种方法。
方法1:使用inotify-tools
sudo apt-get update sudo apt-get install inotify-tools inotify_example.sh的脚本,并添加以下内容:#!/bin/bash # 监视目录 WATCH_DIR="/path/to/your/directory" # 事件类型,例如:CREATE, DELETE, MODIFY等 EVENTS="CREATE,DELETE,MODIFY" # 使用inotifywait命令监视目录 inotifywait -m -r -e "$EVENTS" --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' "$WATCH_DIR" | while read FILE EVENT do # 在这里处理事件 echo "File: $FILE Event: $EVENT" done 修改脚本中的WATCH_DIR变量,将其设置为你想要监视的目录。
为脚本添加可执行权限:
chmod +x inotify_example.sh ./inotify_example.sh 现在,每当指定目录中发生事件时,脚本都会实时处理它们。
方法2:使用libinotify库
sudo apt-get update sudo apt-get install libinotify-dev libinotify_example.c的C文件,并添加以下内容:#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]; // 检查命令行参数 if (argc < 2) { printf("Usage: %s <path-to-watch>\n", argv[0]); exit(EXIT_FAILURE); } // 初始化inotify fd = inotify_init(); if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); } // 添加要监视的目录 wd = inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY); if (wd < 0) { perror("inotify_add_watch"); exit(EXIT_FAILURE); } // 循环读取事件 while (1) { length = read(fd, buffer, BUF_LEN); if (length < 0) { perror("read"); exit(EXIT_FAILURE); } while (i < length) { struct inotify_event *event = (struct inotify_event *) &buffer[i]; if (event->len) { if (event->mask & IN_CREATE) { printf("File %s created\n", event->name); } else if (event->mask & IN_DELETE) { printf("File %s deleted\n", event->name); } else if (event->mask & IN_MODIFY) { printf("File %s modified\n", event->name); } } i += EVENT_SIZE + event->len; } i = 0; } // 移除监视并关闭文件描述符 inotify_rm_watch(fd, wd); close(fd); exit(EXIT_SUCCESS); } gcc -o libinotify_example libinotify_example.c ./libinotify_example /path/to/your/directory 现在,每当指定目录中发生事件时,程序都会实时处理它们。