我正在尝试使用以下命令使用inotify
监视对文件/dev/hvc0
的更改:
#include <stdio.h>
#include <sys/inotify.h>
#include <stdlib.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
#define WATCH_FILE "/dev/hvc0" /* This file should be present
before this program is run */
int main() {
int notify_fd;
int length;
int i = 0;
char buffer[BUF_LEN];
notify_fd = inotify_init();
if (notify_fd < 0) {
perror("inotify_init");
}
int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS);
int length_read = read(notify_fd, buffer, BUF_LEN);
if (length_read) {
perror("read");
}
while (i < length_read) {
struct inotify_event *event =
(struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_ACCESS) {
printf("The file %s was accessed.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("The file %s was modified.\n", event->name);
}
}
}
(void) inotify_rm_watch(notify_fd, wd);
(void) close(notify_fd);
return 0;
}
但是,如果访问/修改了文件,则不会打印。但是,每当我将要监视的路径更改为目录并更改了文件时,它都会打印发生的正确事件。
inotify
是否也可用于监视文件更改?还是我做错了?
谢谢!
我不明白为什么event->len
返回零,可能是因为未返回文件名。但仅出于测试目的,您只需对其进行评论。第二点您对i的处理已损坏,您永远不会在循环中将其重置为0。这使得仅在它们比之前的最长事件长时才考虑后期的inotin事件,这不太可能是您想要的。并且请在while循环中,请输入i += EVENT_SIZE + event->len;
您缺少增加i
的功能。在循环结束前添加它:
根据此answer,看来Linux无法监视特定文件。如果要听特定的文件,则应先听其父目录。