inotify-cpp 使用
一,简介
inotify-cpp 是 Linux 系统调用 inotify
的一个 C++ 封装库。
- 它让你可以监控你文件系统上的文件系统事件。
- 提供面向对象的 C++ 接口,简化对 Linux 内核文件系统事件监控机制的使用,开发者无需直接操作底层系统调用。
- 监听目录或文件的创建、删除、修改、打开等事件,支持递归监控子目录。
- 通过封装复杂的事件处理逻辑(如缓冲区解析、事件队列管理),减少重复代码,降低开发门槛。
地址:GitHub - erikzenker/inotify-cpp: A C++ interface for linux inotify
国内可以使用:项目首页 - inotify-cpp:A C++ interface for linux inotify - GitCode
二,编译
1,获取 inotify-cpp
git clone https://github.com/erikzenker/inotify-cpp.git
cd inotify-cpp
2,编译
mkdir build
cd build
cmake ..
make
编译过程中,出现 fatal error: filesystem: No such file or directory
可以参考:fatal error: filesystem: No such file or directory-CSDN博客
编译测试程序:
# cmake --build . --target inotify_example
三,示例代码解释
root@ubuntu:/home/yjy/PrjMake/test/inotify-cpp/build# cat ../example/main.cpp
#include <inotify-cpp/NotifierBuilder.h> // 引入核心构建器类,用于创建文件系统监听器
#include <inotify-cpp/FileSystemAdapter.h> // 引入文件系统适配器,处理路径和文件操作#include <iostream> // 标准输入输出流,用于打印日志
#include <thread> // C++11线程库,用于异步运行事件循环
#include <chrono> // 时间库,用于设置超时和时间戳using namespace inotify; // 使用inotify命名空间,避免重复书写前缀int main(int argc, char** argv)
{if (argc <= 1) {std::cout << "Usage: ./inotify_example /path/to/dir" << std::endl;exit(0);}// 解析要监控的目录路径inotifypp::filesystem::path path(argv[1]);// 定义预期事件的处理函数(捕获外部作用域的path变量)// 处理用户显式监听的事件,打印事件类型、路径和时间戳auto handleNotification = [&](Notification notification) {std::cout << "Event " << notification.event << " on " << notification.path << " at "<< notification.time.time_since_epoch().count() << " was triggered." << std::endl;};// 定义未预期事件的处理函数(不捕获外部变量)// 处理未在 events 中声明的事件(默认会抛异常,此处改为打印日志)// Notification 对象:包含 event(事件类型)、path(触发路径)、time(时间戳)三个成员auto handleUnexpectedNotification = [](Notification notification) {std::cout << "Event " << notification.event << " on " << notification.path << " at "<< notification.time.time_since_epoch().count()<< " was triggered, but was not expected" << std::endl;};// 定义要监听的文件系统事件集合auto events = { Event::open | Event::is_dir, // 组合事件:目录被打开Event::access, // 文件被访问(读操作)Event::create, // 文件/目录被创建Event::modify, // 文件内容被修改Event::remove, // 文件/目录被删除Event::move }; // 文件/目录被移动或重命名// 使用构建器模式配置监听器(流式接口)auto notifier = BuildNotifier().watchPathRecursively(path) // 递归监控目录及其所有子目录.ignoreFileOnce("fileIgnoredOnce") // 临时忽略该文件(下次修改会触发事件).ignoreFile("fileIgnored") // 永久忽略该文件(所有修改都不触发事件).onEvents(events, handleNotification) // 绑定预期事件与处理函数.onUnexpectedEvent(handleUnexpectedNotification); // 绑定未预期事件处理函数// 在独立线程中运行事件循环(避免阻塞主线程)std::thread thread([&](){ notifier.run(); });// 主线程休眠60秒后终止事件循环std::this_thread::sleep_for(std::chrono::seconds(60));notifier.stop(); // 通知事件循环退出thread.join(); // 等待线程结束并释放资源return 0;
}
整体流程:
1. 解析监控路径 → 2. 定义事件处理逻辑 → 3. 配置监听器参数 → 4. 异步运行事件循环 → 5. 定时终止程序。
使用场景:
适用于自动构建、文件同步、配置热更新等需要实时响应文件变化的场景。