一、inotify
     inotify是内核的一个特性,可以用来监控目录、文件的读写等事件,当监控目标是目录时,inotify除了会监控目录本身,还会监控目录中的文件。inotify的监控功能由如下的几个系统调用完成:inotify_init(2) (or inotify_init1(2)), inotify_add_watch(2), inotify_rm_watch(2), read(2), and close(2).
     inotify的主要操作基于inotify_init 返回的inotify文件描述符,该描述符的作用类似于epoll用到的epoll_fd。inotify在监控目录的时候,不支持对目录的递归监控,即只能监控一层目录,如果需要递归监控的,就需要将这些目录通过inotify_add_watch添加进来。
     inotify目前只能检测到目标文件(夹)发生了什么操作,无法检查出是哪个进程触发的这项操作。(注:fanotify函数接口支持获取触发操作的进程pid,但是fanotify支持的检测类型比inotify少太多,使用者也比较少)
     
     需求:监控/home/sxhlinux/test/test.txt的状态
     
  C语言实现:
#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <errno.h>
#include <string.h>
#include <sys/epoll.h>
 
int main(void)
{
    char *filename = "./log.txt";
 
    int inoti_fd = inotify_init1(IN_CLOEXEC);
    if (inoti_fd == -1) {
        printf("inotify_init failed, %s\n", strerror(errno));
        exit(-1);
    }
 
    int file_fd = inotify_add_watch(inoti_fd, filename, IN_ALL_EVENTS);
    if (file_fd == -1) {
        printf("inotify_add_watch failed, %s\n", strerror(errno));
        exit(-1);
    }
 
    int epoll_fd = epoll_create(5);
    if (epoll_fd == -1) {
        printf("epoll_create failed, %s\n", strerror(errno));
        goto end;
    }
 
    struct epoll_event ev, event[5];
 
    memset(&ev, 0, sizeof(ev));
    ev.events = EPOLLIN | EPOLLET;
    ev.data.fd = inoti_fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, inoti_fd, &ev) == -1) {
        printf("epoll_ctl failed, %s\n", strerror(errno));
        goto end;
    }
 
    int buf_size = sizeof(struct inotify_event) + 64 * sizeof(char);
    struct inotify_event * instance = malloc(buf_size);
    memset(instance, 0, buf_size);
 
    int value = 0;
    while ((value = epoll_wait(epoll_fd, event, 5, -1)) != -1) {
        int i = 0;
        for (i = 0; i < value; i ++) {
            if (event[i].data.fd == inoti_fd) {
                if (read(inoti_fd, instance, buf_size) > 0)
                    printf("file_id is %d, event is %u, cookie is %u, name is %s\n",
                            instance->wd, instance->mask, instance->cookie, instance->name);
                else
                    printf("read inoti_fd failed, %s\n", strerror(errno));
            }
            else
                printf("unknown file_fd %d\n", event[i].data.fd);
        }
    }
 
end:
    inotify_rm_watch(inoti_fd, file_fd);
 
    return 0;
     Python实现:
#!/usr/bin/python
 
import logging
from inotify import adapters
 
_DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
 
_LOGGER = logging.getLogger(__name__)
 
def _configure_logging():
    _LOGGER.setLevel(logging.DEBUG)
    ch = logging.FileHandler('./record', 'a')
    formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
    ch.setFormatter(formatter)
    _LOGGER.addHandler(ch)
 
def _main():
    i = adapters.Inotify()
    i.add_watch('/var/lib/logrotate.status')
 
    for event in i.event_gen():
        if event:
            (header, type_names, watch_path, filename) = event
            print ("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s WATCH-PATH=[%s] FILENAME=[%s]",\
            header.wd, header.mask, header.cookie, header.len, type_names, watch_path.decode('utf-8'), filename.decode('utf-8'))
            _LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s WATCH-PATH=[%s] FILENAME=[%s]",\
            header.wd, header.mask, header.cookie, header.len, type_names, watch_path.decode('utf-8'), filename.decode('utf-8'))
 
if __name__ == '__main__':
    _configure_logging()
    _main()
     shell命令(依赖inotify-tools软件包):
#监控log.txt发生的操作,并输出到record文件中,另外inotifywait命令的-r选项支持递归遍历
$ inotifywait -m log.txt -o record
 
#inotifywatch 命令则用于统计一段时间内,某个文件所发生操作的统计数据
#上述的两个命令的具体用法参照man手册
二、systemtap监控
     systemtap可以监控系统调用,我们使用stap带的一个监控inode的插件inodewatch.stp 来实现对文件的监控。
$ yum install systemtab -y
$ yum install kernel-debug-debuginfo     #stap监控系统调用需要
$ stap -ve 'probe begin { log("hello world") exit() }'     #测试stap是否安装成功
$ ls -i log.txt      #查看要监控文件的inode号 2360637
$ df -h      #查看log.txt所在的磁盘分区
$ cat /proc/partitions     #查看各个磁盘分区的major、minor号 8 2
$ stap /usr/share/doc/systemtap-1.6/examples/io/inodewatch.stp 0x8 0x2 2360637     #监控log.txt即(0x8 0x2 2360637)所进行的操作,同时会显示出执行操作的进程ID

  

文件读写监控(inotify, systemtap)的更多相关文章

  1. Linux 文件操作监控inotify功能及实现原理【转】

    转自:http://blog.chinaunix.net/uid-26585427-id-5012973.html 1. inotify主要功能 它是一个内核用于通知用户空间程序文件系统变化的机制. ...

  2. 使用pt-ioprofile监控数据库io文件读写情况

    我们在做IO密集型的应用程序的时候,比如MySQL数据库,通常系统的表现取决于workload的类型. 比如我们要调优,我们就必须非常清楚的知道数据的访问规律,收集到足够的数据,用来做调优的依据. 有 ...

  3. Linux下使用inotify实现对文件的监控

    项目中,要实现用户通过网页设置參数,后台接收数据然后写串口. 网页写数据到本地文件,使用inotify监控文件的IN_MODIFY事件.当文件被改动,然后触发写串口事件. 第一个程序只把要监控的文件增 ...

  4. IO异步,读写压缩文件,监控文件系统

    这节结尾IO,讲一下异步操作文件,读写压缩文件,监控文件系统这三个知识点. 异步操作文件:     说到异步,必然要了解的是async和await这两个关键字(异步详情点击基于任务的异步编程(Task ...

  5. Sersync实现触发式文件同步 替代inotify和rsync

    Sersync实现触发式文件同步 替代inotify和rsync Pyinotify是一个Python模块,用来监测文件系统的变化. Pyinotify依赖于Linux内核的功能—inotify(内核 ...

  6. python学习之文件读写,序列化(json,pickle,shelve)

    python基础 文件读写 凡是读写文件,所有格式类型都是字符串形式传输 只读模式(默认) r  f=open('a.txt','r')#文件不存在会报错 print(f.read())#获取到文件所 ...

  7. 【Win 10 应用开发】文件读写的三种方案

    本文老周就跟伙伴们探讨一下关于文件读写的方法.总得来说嘛,有三种方案可以用,而且每种方案都各有特色,也说不上哪种较好.反正你得记住老祖宗留给我们的大智慧——事无定法,灵活运用者为上. OK,咱们开始吧 ...

  8. c语言文件读写操作总结

    C语言文件读写操作总结 C语言文件操作 一.标准文件的读写 1.文件的打开 fopen() 文件的打开操作表示将给用户指定的文件在内存分配一个FILE结构区,并将该结构的指针返回给用户程序,以后用户程 ...

  9. ActionScript 3.0入门:Hello World、文件读写、数据存储(SharedObject)、与JS互调

    近期项目中可能要用到Flash存取数据,并与JS互调,所以就看了一下ActionScript 3.0,现把学习结果分享一下,希望对新手有帮助. 目录 ActionScript 3.0简介 Hello ...

随机推荐

  1. with补充知识点

    import threading,queue,time import contextlib @contextlib.contextmanager def fun(list_1,val): list_1 ...

  2. webform中 ajax调用后台方法(非webservice)

    方法一:通过创建一个没有内容的窗体 后台: public partial class Ajax_ShoppingCart : System.Web.UI.Page { bookdbDataContex ...

  3. 【转】mysql中文乱码的一点理解

    我们自己鼓捣mysql时,总免不了会遇到这个问题:插入中文字符出现乱码,虽然这是运维先给配好的环境,但是在自己机子上玩的时候咧,总得知道个一二吧,不然以后如何优雅的吹牛B. 如果你也遇到了这个问题,咱 ...

  4. uboot移植前奏

    Tiny4412开发板硬件版本为:       底板:  Tiny4412/Super4412SDK 1506        核心板:Tiny4412 - 1412 1.下载u-boot源代码,建立u ...

  5. RecyclerView学习笔记

    主要方法: setLayoutManager:设置显示方式,有LinearLayoutManager(像ListView一样的纵向列表布局),有GridLayoutManager(网格布局),有Sta ...

  6. SVN打基线

    分成trunk.tags.branches的话,那直接从trunk copy 到tags下面就可以或者按照你自己的目录,只要规定好就行 选择要打基线的项目的根目录,右击鼠标,在弹出的菜单中选择“分支/ ...

  7. UVa 908 - Re-connecting Computer Sites

    题目大意:有n个网站,由m条线路相连,每条线路都有一定的花费,找出连接所有线路的最小花费. 最小生成树问题(Minimal Spanning Tree, MST),使用Kruskal算法解决. #in ...

  8. iOS 之 网络 NSURLSession

    NSURLSession相比NSURLConnection功能更强大,是更上层的网络封装.相比而言,普通应用场景下NSURLSession没有什么优势,但是,在程序切换到后台的情况下,NSURLSes ...

  9. iOS 之 二维码生成与扫描(LBXScan)

    参考:https://github.com/MxABC/LBXScan 步骤如下: 1. 下载 通过参考网址进行下载. 2. 导入 导入整个LBXScan文件夹 3. 配置 在pch中加入 #impo ...

  10. Spring mvc系列一之 Spring mvc简单配置

    Spring mvc系列一之 Spring mvc简单配置-引用 Spring MVC做为SpringFrameWork的后续产品,Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块 ...