linux 通过notify机制检测/home/usr/a.txt是否发生更新 C语言示例
时间: 2023-07-31 15:09:59 浏览: 49
以下是一个使用C语言编写的示例程序,利用inotify机制监控文件变化:
```c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/inotify.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
int main(int argc, char* argv[]) {
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
}
wd = inotify_add_watch(fd, "/home/usr/a.txt", IN_MODIFY);
while (1) {
i = 0;
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
}
while (i < length) {
struct inotify_event* event = (struct inotify_event*)&buffer[i];
if (event->mask & IN_MODIFY) {
printf("File /home/usr/a.txt has been modified!\n");
}
i += EVENT_SIZE + event->len;
}
}
(void)inotify_rm_watch(fd, wd);
(void)close(fd);
return 0;
}
```
程序中使用inotify_init()函数初始化一个inotify实例,然后使用inotify_add_watch()函数添加要监控的文件或目录,并指定要监控的事件类型(如IN_MODIFY表示文件被修改)。程序进入无限循环,使用read()函数读取inotify实例的事件信息,然后遍历每个事件,检查是否是文件修改事件,如果是则输出消息。
请注意,如果你要运行此程序,需要在编译时链接inotify库,例如:
```bash
gcc -o inotify_example inotify_example.c -linotify
```
同时,你需要在程序中指定要监控的文件路径,例如本例中的"/home/usr/a.txt"。