Linux Device Driver >> fanotify
監看某個特定資料夾的OPEN事件
參考資訊:
1. fanotify-monitor-one-specific-folder-not-the-whole-filesystem
2. how-do-i-program-for-linuxs-new-fanotify-file-system-monitoring-feature
main.c
#include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/fanotify.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char **argv) { int fan = -1; char buf[4096] = {0}; char path[255] = {0}; char fdpath[32] = {0}; ssize_t buflen = 0, linklen = 0; struct fanotify_event_metadata *metadata = NULL; fan = fanotify_init(FAN_CLASS_NOTIF, O_RDONLY); fanotify_mark(fan, FAN_MARK_ADD, FAN_OPEN | FAN_EVENT_ON_CHILD, AT_FDCWD, "/tmp"); while (1) { buflen = read(fan, buf, sizeof(buf)); metadata = (struct fanotify_event_metadata*)&buf; while (FAN_EVENT_OK(metadata, buflen)) { if (metadata->mask & FAN_Q_OVERFLOW) { continue; } sprintf(fdpath, "/proc/self/fd/%d", metadata->fd); linklen = readlink(fdpath, path, sizeof(path) - 1); path[linklen] = '\0'; printf("%s opened by process %d.\n", path, (int)metadata->pid); close(metadata->fd); metadata = FAN_EVENT_NEXT(metadata, buflen); } } }
編譯、執行
$ gcc main.c -o test $ sudo ./test
接著在另一個視窗輸入如下命令
$ touch /tmp/test
結果
/tmp/test opened by process 15410.