当前位置: 代码迷 >> 综合 >> Linux/Unix 使用inotify,hook函数来监控文件事件
  详细解决方案

Linux/Unix 使用inotify,hook函数来监控文件事件

热度:7   发布时间:2024-01-20 01:58:35.0

在实际开发中有时候会遇到许多文件的操作,或者需要对文件事件进行排查。当代码复杂度高到一定程度或者本身项目是使用多线程的时候(磁盘文件IO使用多线程本身并不是一种好的方案)。需要检测文件的事件来进行一些bug分析,这就需要用到文件IO事件的操作。

一,使用系统API Inotify来监控文件事件

在Linux系统中可以使用inotify系列函数来进行文件事件的监控。

可以使用inotify函数来完成这项工作

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/inotify.h>#define EVENT_SIZE      (sizeof (struct inotify_event))
#define BUF_LEN         (10 * (EVENT_SIZE + 256))static const char * filetype[] = {"directory", "file"};static void
displayInotifyEvent(struct inotify_event * event)
{const char * type = (event->mask & IN_ISDIR) ? filetype[0] : filetype[1];if(event->len) {if(event->mask & IN_CREATE) {printf("The %s %s was created.\n", type, event->name);}else