Linux inotify监控文件变化的示例

代码

#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博客

Inotify机制-CSDN博客

C语言read()函数:读文件函数_c语言read函数-CSDN博客

 read(2) - Linux manual page

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值