linux fanotify和inotify

工作中用到fanotify和inotify,记录下
Fanotify 有三个个基本的模式:directed,per-mount 和 global。其中,directed 模式和 inotify 类似,直接工作在被监控的对象的 inode 上,一次只可以监控一个对象。因此需要监控大量目标时也很麻烦。Global 模式则监控整个文件系统,任何变化都会通知 Listener。Per-mount 模式工作在 mount 点上,比如磁盘 /dev/sda2 的 mount 点在 /home,则 /home 目录下的所有文件系统变化都可以被监控,这其实可以被看作另外一种 Global 模式。
fanotify能监控的类型比inotify少
fanotify可以返回进程pid
fanotify需要root权限

fanotify

#define _GNU_SOURCE    
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/fanotify.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <set>
using namespace std;

set<string> sset;


static void handle_events(int fd)
{
    const struct fanotify_event_metadata *metadata;
    struct fanotify_event_metadata buf[200];
    ssize_t len;
    char path[PATH_MAX];
    ssize_t path_len;
    char procfd_path[PATH_MAX];
    struct fanotify_response response;


    for(;;) 
    {

        len = read(fd, (void *) &buf, sizeof(buf));
        if (len == -1 && errno != EAGAIN) 
        {
            perror("read");
            exit(EXIT_FAILURE);
        }
        
        if (len <= 0)
            continue;
        
        metadata = buf;


        while (FAN_EVENT_OK(metadata, len)) 
        {
            if (metadata->vers != FANOTIFY_METADATA_VERSION) 
            {
                fprintf(stderr,"Mismatch of fanotify metadata version.\n");
                continue;
            }

            //printf ("receive event time %llu \n",time(NULL));
            if (metadata->fd >= 0) 
            {
                if ((metadata->mask & FAN_MODIFY) || (metadata->mask & FAN_OPEN))
                {
                    
                    snprintf(procfd_path, sizeof(procfd_path),
                            "/proc/self/fd/%d", metadata->fd);
                    path_len = readlink(procfd_path, path,
                                        sizeof(path) - 1);
                    if (path_len == -1) {
                        perror("readlink");
                        exit(EXIT_FAILURE);
                    }

                    path[path_len] = '\0';
                    string Path = path;
                    if (sset.find(Path) != sset.end())
                    {
                        printf("receive: %d\n", metadata->mask);
                        if (metadata->mask & FAN_MODIFY)
                            printf("FAN_MODIFY: \n");
                        if (metadata->mask & FAN_OPEN)
                            printf("FAN_open: \n");
                        printf("PID  %d op File %s\n",metadata->pid , path);
                    }
                    
                }
                
                close(metadata->fd); 
            }

            /* Advance to next event */

            metadata = FAN_EVENT_NEXT(metadata, len);
        }
    }
}

int main(int argc, char *argv[])
{
    char buf;
    int fd, poll_num;
    nfds_t nfds;
    struct pollfd fds[2];
    sset.insert(string("/home/zxdbtest/data/data/py/py.ibd"));
    /* Check mount point is supplied */

    if (argc < 2) 
    {
        exit(EXIT_FAILURE);
    }

    printf("FAN_MODIFY: %d\n", FAN_MODIFY);
    printf("FAN_open: %d\n", FAN_OPEN);
    //FAN_NONBLOCK 是非阻塞  read时不阻塞,导致cpu占用过高,不建议设置
    fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT |FAN_NONBLOCK,
                        O_RDONLY | O_LARGEFILE);
    if (fd == -1) 
    {
        perror("fanotify_init");
        exit(EXIT_FAILURE);
    }
    for (int i=1;i<argc;i++)
    {
        printf("add watch : %s\n",argv[i] );
        //FAN_MARK_MOUNT 是监控挂载点
        if (fanotify_mark(fd, FAN_MARK_ADD|FAN_MARK_MOUNT  ,FAN_MODIFY | FAN_OPEN, -1,argv[i]) == -1) 
        {
            perror("fanotify_mark");
            exit(EXIT_FAILURE);
        }
    }
    handle_events(fd);
    printf("Listening for events stopped.\n");
    exit(EXIT_SUCCESS);
}

inotify

#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/inotify.h>
#include<limits.h>
#include<fcntl.h>
#include<sys/ioctl.h>
#include<sys/time.h>

#define BUF_LEN 1000


/*
struct inotify_event {
   int      wd;       // Watch descriptor 
   uint32_t mask;     // Mask of events 
   uint32_t cookie;   // Unique cookie associating related  events (for rename(2))
   uint32_t len;      // Size of name field 
   char     name[];   // Optional null-terminated name 
};
*/

//若不将inotify的文件符加入到 select中  删除自身(直接监控file)不会被捕捉到
int event_check (int fd)
{
    fd_set rfds;
    FD_ZERO (&rfds);
    FD_SET (fd, &rfds);
    //timeout=NULL(阻塞:select将一直被阻塞,直到某个文件描述符上发生了事件)
    return select (fd+1, &rfds, NULL, NULL, NULL);//第一个参数是加入的fd最大值加一
}

void handleInotifyEvents(int inotifyFd, fd_set &inputs)
{
    struct inotify_event *event;
    char *p;
    char buf[BUF_LEN];
    ssize_t numRead;
    fd_set testfds;
    for(;;)  
    {
        if (event_check (inotifyFd) > 0)
        {
            numRead = read(inotifyFd,buf,BUF_LEN);
            if(numRead == -1)
            {
                printf("read error\n");
            }

            printf("read %ld bytes from inotify fd\n",(long)numRead);
            for(p = buf; p < buf+numRead;)
            {
                event = (struct inotify_event *)p;
                if(event ->mask & IN_DELETE_SELF)  //判断是那个文件进行了更改
                {
                    printf(" %s IN_DELETE_SELF\n",event->name);//这里name一般为空,所以使用时一般要提前保存好
                }
                p += sizeof(struct inotify_event)+ event->len;
            }
        }
    } 
}

int main(int argc,char **argv)
{
    int inotifyFd;  
    fd_set inputs;
    
    if(argc < 2)
    {
        printf("error\n");
    }

    inotifyFd = inotify_init(); //系统调用可创建一新的inotify实例  初始化实例
    if(inotifyFd == -1)
    {
        printf("init error\n");
        return 0;
    }
    for (int i=1;i<argc;i++)
    {
        printf("add watch : %s\n",argv[i] );
        int wd = inotify_add_watch(inotifyFd,argv[i],IN_DELETE_SELF);  //系统调用inotify_add_watch()可以追加新的监控项
        if(wd < 0)
        {
            printf("add watch error \n");
        }
        printf("watching %s using wd =  %d\n", argv[i], wd);
    }
    
    handleInotifyEvents(inotifyFd, inputs);
    close(inotifyFd);
    return 0;
}

发布了169 篇原创文章 · 获赞 4 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览