gpt4 book ai didi

c - 在 C 中通知问题

转载 作者:太空狗 更新时间:2023-10-29 11:13:46 26 4
gpt4 key购买 nike

我想监控对文件的修改,但它不起作用。输入示例:./es file_to_watch

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <linux/limits.h>
#include <sys/inotify.h>

#define BUF_LEN sizeof(struct inotify_event) + NAME_MAX + 1 /*buffer to store the data of events*/

int main( int argc, char *argv[]){
int fd, wd, length;
char buffer[BUF_LEN];
struct inotify_event *event;

if(argc < 2){
exit(1);
}
else{
fd = inotify_init();
if(fd < 0){
perror("inotify_init");
}

wd = inotify_add_watch(fd, argv[1], IN_OPEN | IN_MODIFY | IN_DELETE);
if (wd == -1)
return(1);
else{

while(1){
length = read(fd, buffer, BUF_LEN);
if(length == -1)
return(0);

event = (struct inotify_event *) &buffer;
if(event->len){
if(event->mask & IN_OPEN){
printf( "file %s was open.\n", event->name );
}
else if(event->mask & IN_MODIFY){
printf( "file %s was modify.\n", event->name );
}
else if(event->mask & IN_DELETE){
printf( "file %s was delete.\n", event->name );
break;
}
}
}
inotify_rm_watch(fd, wd);
close(fd);
}
}
return(0);
}

当我尝试打开文件时,没有任何反应。当我尝试更改或取消它时,同样的事情发生了。程序应该在文件被删除时结束。谢谢。

最佳答案

你有几个问题(来自 inotify man page )

  1. name 字段仅在您查看目录时出现。所以在printf中使用event->name是错误的,你应该打印argv[1]
    The name field is present only when an event is returned for a file
inside a watched directory; it identifies the file pathname relative
to the watched directory. This pathname is null-terminated, and may
include further null bytes ('\0') to align subsequent reads to a
suitable address boundary.
  1. 在您的情况下,event->mask 永远不会等于 IN_DELETE,因为
    IN_DELETE (+)
File/directory deleted from watched directory.

but instead
    IN_IGNORED
Watch was removed explicitly (inotify_rm_watch(2)) or
automatically (file was deleted, or filesystem was
unmounted). See also BUGS.

when the file is deleted.

我建议您改为查看目录,并检查 event->name 以查看它是否与您提供的 argv[1] 匹配。

您还应该在read 之后有一个循环,以将所有可能的inotify_event * 读取到buffer。您可以通过指向 buffer 开头的指针并在每次迭代中将其增加 sizeof(struct inotify_event) + event->len 来实现。

关于c - 在 C 中通知问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27548893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com