在这段代码中,我试图在同一时间监控两个路径。为此我使用了
while(1)
。但我面临的问题是,每当我运行这段代码时,它给我两次相同的结果,就像这样。
Giving result
Pathname1 "file" is modified
Pathname1 "file" is modified
Expected result
Pathname1 "file" is modified
我调试了代码。在断开主函数并跨过它之后,下一个命令停在这一行length = read(fd, buffer, EVENT_BUF_LEN )
。每当我在这个长度变量命令之后断开一行,程序就开始,在修改文件之后,程序在这一行停止struct inotify_event *event = ( struct inotify_event *)&buffer[i];
。尽管程序不应该中断。
我还用IN_CLOSE_WRITE
代替了IN_MODIFY
,但结果没有变化。
typedef struct{
int length, fd, wd1, wd2;
char buffer[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
} notification;
notification inotify;
int getNotified(char *pathname1, char *pathname2){
inotify.fd = inotify_init();
inotify.wd1 = inotify_add_watch(inotify.fd, pathname1, IN_MODIFY);
inotify.wd2 = inotify_add_watch(inotify.fd, pathname2, IN_MODIFY);
while(1){
inotify.length = read(inotify.fd, inotify.buffer, EVENT_BUF_LEN);
int i = 0;
while(i < inotify.length){
struct inotify_event *event = (struct inotify_event *)&inotify.buffer[i];
if(event->len){
if(event->mask & IN_MODIFY){
if(event->wd == inotify.wd1){
printf("Pathname1 '%s' is modified\n", event->name);
break;
if(event->wd == inotify.wd2){
printf("Pathname2 '%s' is modified\n", event->name);
break;
i += EVENT_SIZE + event->len;
inotify_rm_watch(inotify.fd, inotify.wd1);
inotify_rm_watch(inotify.fd, inotify.wd2);
close(inotify.fd);
exit(0);