用 inotify 监视文件系统的变化

可以用 Linux 2.6 kenel 提供的 inotify 机制来监控文件系统的变化,例如增加文件,删除文件,修改文件等

下面是一个例子程序,可用来监控一个目录,如果在此目录下进行创建文件、删除文件、修改文件的操作,会有提示信息打印到屏幕上

 

#include  < sys / inotify.h >
#include 
< stdio.h >
#include 
< errno.h >
#include 
< sys / types.h >
#include 
< unistd.h >
#include 
< sys / ioctl.h >

#define  BUF_LEN   4096

int  main( int  argc,  char   ** argv)
{

    
if(argc < 2{
        printf(
"Usage: %s [directory] ", argv[0]);
        
return -1;
    }


    
int fd;

    fd 
= inotify_init();

    
if(fd == -1{
        printf(
"failed in inotify_init, %d ", errno);
        
return -1;
    }


    
int wd1, wd2;    
ADD_AGAIN:

    wd1 
= inotify_add_watch(fd, argv[1], IN_DELETE|IN_MODIFY|IN_CREATE|IN_IGNORED);
    
if(wd1 == -1{
        perror(
"inotify_add_watch");
        
return -1;
    }
 else 
        printf(
"new watch fd %d ", wd1);
/*
    wd2 = inotify_add_watch(fd, "/etc", IN_ACCESS|IN_MODIFY);
    if(wd2 == -1) {
        perror("inotify_add_watch");
        return -1;
    }
*/


    
char buf[BUF_LEN] __attribute__ ((aligned(4)));
    ssize_t len, i 
= 0;

    unsigned 
int queue_len;
    
int ret;

while (1{
    i 
= 0;
    
    ret 
= ioctl(fd, FIONREAD, &queue_len);
    
if(ret < 0{
        perror(
"ioctl");
    }
 

    len 
= read(fd, buf, BUF_LEN);

    
while(i < len) {
        
struct inotify_event *event = (struct inotify_event*)&buf[i];
        
        printf(
"wd=%d mask=%d cookie=%d len=%d dir=%s ",
            
event->wd, event->mask, event->cookie, event->len, (event->mask & IN_ISDIR) ? "yes" : "no");
        
        
if(event->len) 
            printf(
"name=%s "event->name);
        
        
if(event->mask & IN_IGNORED) {
            printf(
"ignored, add again ");
            
if(0 != inotify_rm_watch(fd, event->wd)) 
                perror(
"inotify_rm_watch");
            
goto ADD_AGAIN;
        }

            
        i 
+= sizeof(struct inotify_event) + event->len;
    }

}


    
return 0;
}


 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值