inotify
是 Linux 內核提供的一種文件系統事件監控機制,它在 Debian 系統中廣泛使用。然而,inotify
并不是跨平臺的,因為它特定于 Linux。如果你需要在不同操作系統(如 Windows、macOS 和 Linux)上實現文件系統事件的監控,你需要使用跨平臺的解決方案。
以下是一些跨平臺的文件系統事件監控庫和方法:
watchdog
庫watchdog
是一個跨平臺的文件系統事件監控庫,支持 Windows、macOS 和 Linux。
watchdog
pip install watchdog
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
print(f'File {event.src_path} has been created')
def on_deleted(self, event):
print(f'File {event.src_path} has been deleted')
def on_modified(self, event):
print(f'File {event.src_path} has been modified')
if __name__ == "__main__":
path = "/path/to/monitor"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
chokidar
庫chokidar
是一個高效的文件系統監控庫,支持跨平臺。
chokidar
npm install chokidar
const chokidar = require('chokidar');
// 監控目錄
const watcher = chokidar.watch('/path/to/monitor', {
ignored: /(^|[\/\\])\../, // 忽略隱藏文件
persistent: true
});
// 添加事件監聽器
watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`))
.on('unlink', path => console.log(`File ${path} has been removed`))
.on('error', error => console.error(`Error: ${error}`));
Boost.Asio
和 boost::filesystem
如果你更喜歡使用 C++,可以使用 Boost.Asio
和 boost::filesystem
來實現跨平臺的文件系統監控。
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
namespace fs = boost::filesystem;
void watch_directory(const std::string& path) {
fs::recursive_directory_iterator end_itr;
for (fs::recursive_directory_iterator itr(path); itr != end_itr; ++itr) {
if (fs::is_directory(*itr)) {
std::cout << "Directory: " << itr->path() << std::endl;
} else {
std::cout << "File: " << itr->path() << std::endl;
}
}
}
int main() {
std::string path = "/path/to/monitor";
watch_directory(path);
return 0;
}
如果你需要在 Debian 系統中實現跨平臺的文件系統事件監控,推薦使用 watchdog
(Python)或 chokidar
(Node.js)。這些庫提供了簡單易用的 API,并且支持多種操作系統。