linux inotify例子,关于Inotify对linux文件系统的监控

本文介绍了一个使用inotify实现的文件监控程序。该程序能够监听指定文件或目录的变化,并打印出变化类型、对象类型及名称等详细信息。通过inotify_init、inotify_add_watch和inotify_rm_watch等系统调用,程序实现了对文件变动事件的有效捕捉。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include

#include

#include

_syscall0(int, inotify_init)

_syscall3(int, inotify_add_watch, int, fd, const char *, path, __u32, mask)

_syscall2(int, inotify_rm_watch, int, fd, __u32, mask)

char * monitored_files[] = {

"./tmp_file",

"./tmp_dir",

"/mnt/sda3/windows_file"

};

struct wd_name {

int wd;

char * name;

};

#define WD_NUM 3

struct wd_name wd_array[WD_NUM];

char * event_array[] = {

"File was accessed",

"File was modified",

"File attributes were changed",

"writtable file closed",

"Unwrittable file closed",

"File was opened",

"File was moved from X",

"File was moved to Y",

"Subfile was created",

"Subfile was deleted",

"Self was deleted",

"Self was moved",

"",

"Backing fs was unmounted",

"Event queued overflowed",

"File was ignored"

};

#define EVENT_NUM 16

#define MAX_BUF_SIZE 1024

int main(void)

{

int fd;

int wd;

char buffer[1024];

char * offset = NULL;

struct inotify_event * event;

int len, tmp_len;

char strbuf[16];

int i = 0;

fd = inotify_init();

if (fd < 0) {

printf("Fail to initialize inotify.\n");

exit(-1);

}

for (i=0; imask & IN_ISDIR) {

memcpy(strbuf, "Direcotory", 11);

}

else {

memcpy(strbuf, "File", 5);

}

printf("Object type: %s\n", strbuf);

for (i=0; iwd != wd_array[i].wd) continue;

printf("Object name: %s\n", wd_array[i].name);

break;

}

printf("Event mask: %08X\n", event->mask);

for (i=0; imask & (1

event = (struct inotify_event *)(offset + tmp_len);

offset += tmp_len;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值