Linux文件监控方法

Linux系统开发程序,有时候需要监控配置文件的变化,做出相应操作,下面将介绍常用的文件、目录监控方法:

函数介绍:

1.Inotify系列函数:

Inotify_init(void)

系统返回一个文件描述符,使用完毕需要释放(close)

2.Inotify_add_watch(int fd, const char *pathname, unsigned int mask)

添加对指定文件的监控,可以选择需要监控的事件(设置mask);

3.Inotify_rm_watch(int fd, unsigned int wd)

从fd指定的inotify实例中,删除wd指定的监控项

那么inotify事件有哪些?

1.常见的事件如下:

IN_ACCESS:文件被访问(read)

IN_ATTRIB:文件元数据改变

IN_CLOSE_WRITE:关闭为了写入而打开的文件

一般我们可以使用read从fd中读取事件,当无事件发生,则read会阻塞等待,当有事件发生,则返回inotify_event结构:

Struct inotify_event{

Int wd;

Unsigned int mask

Unsigned int cookie;

Unsigned int len;

Char name\[\];

};

下面用一个简单的示例演示循环监控文件变化:

复制代码
int ret = 0;
char buffer[MAX_BUFF] = {0};
int fd = inotify_init();

if(fd < 0){
    perror("init inotify failed.");
    return;
}

int wd = inotify_add_watch(fd, "/home/test.txt", IN_MODIFY | IN_CLOSE_WRITE | IN_IGNORED | IN_ATTRIB);//这里加了两个事件,稍后介绍

if(wd < 0){
    printf("cannot add watch for test.txt.\n");
    close(fd);//释放
    return;
}

fd_set rfds;
while(1){
    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);
    ret = select(fd+1, &rfds, NULL, NULL, NULL);//监控read
    if(ret <= 0){//如果设置超时,可以做一些其他事情
        continue;
    }
    
    //event happened, so something
    bzero(buffer, sizeof(buffer));
    bet = (0 | read(fd, buffer, MAX_BUFF));
    if(ret < 0){
        printf("read inotify failed.");
        break;
    }

    int index = 0;
    while(index < ret){
        struct inotify_event *pevent = (struct inotify_event*)&buffer[index];
        unsigned int event_size = offsetof(struct inotify_event, name) + pevent->len;
        index += (0 | event_size);
        printf("event[wd:%d,mask:%u,cookie:%u,len:%u].", pevent->wd, pevent->mask, pevent->cookie, pevent->len);
        if(pevent->mask & IN_MODIFY){
           //do something
        }

        if(pevent->mask & IN_CLOSE_WRITE){
            //do something
        }

        if((pevent->mask & IN_IGNORED) || (pevent->mask & IN_ATTRIB)){
       //当触发IN_IGNORED或IN_ATTRIB事件时,需要重新调用inotify_add_watch,否则就只能检测一次,比如我们vi或mv文件时就会出现此种情况
            wd = inotify_add_watch(fd, "/home/test.txt", IN_MODIFY | IN_CLOSE_WRITE | IN_IGNORED | IN_ATTRIB );
        }
    }//end while index
}//end while 1

inotify_rm_watch(fd,wd);
close(fd);

参考文档:https://blog.flowlore.com/passages/inotify-shi-yong-jiao-cheng/

相关推荐
凡人叶枫10 小时前
Effective C++ 条款28:避免使用 handles 指向对象内部
linux·服务器·开发语言·c++·嵌入式开发
AI帮小忙10 小时前
Debian系linux操作系统里安装OpenClaw
linux·运维·debian
极创信息10 小时前
Linux挖矿病毒深度清理实战教程,从进程隐藏、Rootkit驻留到彻底根除
java·大数据·linux·运维·安全·tomcat·健康医疗
zwenqiyu10 小时前
P5283 [十二省联考 2019] 异或粽子题解
c++·学习·算法
Queenie_Charlie10 小时前
哈夫曼树
数据结构·c++·哈夫曼树
lihao lihao11 小时前
Linux信号
开发语言·c++·算法
大白话_NOI11 小时前
【洛谷 P2249】查找(深基 13. 例 1)+ 详细分析
c++·算法
weixin_3077791311 小时前
Python写入Shell文件使用Linux系统的换行符
linux·开发语言·python·自动化
智者知已应修善业11 小时前
【51单片机2个外部中断显示中断历时,初始化8左移3位共阳数码管】2024-6-6
c++·经验分享·笔记·算法·51单片机
码之气三段.12 小时前
edu158-B
c++