代码
#include <iostream>
#include <sys/inotify.h> //inotify_init inotify_add_watch inotify_rm_watch
#include <unistd.h> //extern int close (int __fd); read (int __fd, void *__buf, size_t __nbytes)
#include <memory>
#include <thread>
#include <string.h> //memset
#include <iomanip> // std::setfill std::setw
int main(int argc,char** argv)
{
if (argc != 2) {
std::cout << "Usage:"<<argv[0]<<" filename"<<std::endl;
return 1;
}
uint8_t fd = inotify_init();
if (fd == -1) {
std::cout << "Failed to initialize inotify.\n";
return 1;
}
uint8_t wd = inotify_add_watch(fd, argv[1], IN_MODIFY);
if (wd == -1) {
std::cout << "Failed to add watch.\n";
return 1;
}
std::cout<<"sizeof(inotify_event):"<<sizeof(inotify_event)<<std::endl;
std::unique_ptr<std::thread> inotifyTread = std::make_unique<std::thread>(std::thread([&](void){
char buffer[1024];
while (true) {
ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead == -1) {
std::cout << "Failed to read events.\n";
break;
}
std::cout<<"\nbytesRead:"<<bytesRead<<std::endl;
for (ssize_t i = 0; i < bytesRead; i += sizeof(inotify_event)) {
inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
std::cout<<"event->mask:0x"<<std::hex<<std::setfill('0')<<std::setw(8)<<event->mask<<std::endl;
if (event->mask & IN_MODIFY) {
std::cout << "File "<<argv[1]<<" modified"<<std::endl;
// do something
}
}
memset(buffer, 0, sizeof(buffer));
}
}));
while(true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
inotifyTread.reset();
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
运行
参考博客
Linux inotify功能及原理(inotify_init、inotify_add_watch、inotify_rm_watch、read)_inotify原理-CSDN博客
Linux Inotify详解和使用_linux inotify用法-CSDN博客