简体   繁体   English

当文件被删除并再次创建时,inotify停止监视文件

[英]inotify stops monitoring file when the file is deleted and created again

I encounter some problem when using inotify. 使用inotify时遇到一些问题。 I use inotify to monitor changes on files. 我使用inotify监视文件更改。 Here is my code: 这是我的代码:

int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", IN_ALL_EVENTS);
int bufSize = 1000;
char *buf = new char[bufSize];
memset(buf, 0, sizeof(buf));
int nBytes = read(fd, buf, bufSize - 1);
cout << nBytes << " bytes read" << endl;
inotify_event *eventPtr = (inotify_event *)buf;
int offset = 0;
while (offset < nBytes)
{
    cout << eventPtr->mask << endl;
    offset += sizeof(inotify_event) + eventPtr->len;
    eventPtr = (inotify_event *)(buf + offset);
}
delete []buf;

If I delete "/root/temp" and re-create such a file, any changes to this file is not monitored by inotify, anyone how is this? 如果删除“ / root / temp”并重新创建这样的文件,则inotify不会监视对此文件的任何更改,这是怎么回事? Thanks. 谢谢。

cheng

That's because inotify monitors the underlying inode , not the filename. 这是因为inotify 监视底层的inode而不是文件名。 When you delete that file, the inode you're currently watching becomes invalid, therefore, you must invoke inotify_rm_watch . 删除该文件时,当前正在监视的inode无效,因此,必须调用inotify_rm_watch If you want to monitor a new file with the same name, but a different inode, you must detect when it's created by monitoring its parent folder. 如果要监视名称相同但索引节点不同的新文件,则必须通过监视其父文件夹来检测其创建时间。

The other two answers are correct. 其他两个答案是正确的。 Another useful point is that inotify tells you when the watch is invalidated. 另一个有用的点是inotify会告诉您手表何时失效。

mask & IN_IGNORED

will be non-zero. 将为非零。 IN_IGNORED is set when: IN_IGNORED情况下设置IN_IGNORED

"Watch was removed explicitly (inotify_rm_watch(2)) or automatically (file was deleted, or file system was unmounted)." “已显式删除了监视(inotify_rm_watch(2))或已自动删除了该文件(已删除文件或已卸载文件系统)。”

So, as noted, when this is set, you can rewatch the file (and/or the directory if the file has not yet been re-created). 因此,如前所述,设置此选项后,您可以重新监视文件(如果尚未重新创建文件,则可以重新监视目录)。

Whenever you use an API, READ THE DOCUMENTATION . 每当您使用API​​时,请阅读DOCUMENTATION

inotify works using the unique file identifer inode, not a filename. inotify使用唯一的文件标识符inode而不是文件名来工作。 The entire Linux kernel works with inodes in fact. 整个Linux内核实际上都与inode一起使用。 Filenames are only a means to look up inodes. 文件名只是查找inode的一种方法。

To get what you want you need to monitor the /root directory. 要获得所需的内容,您需要监视/ root目录。 It will report a creation event when a file is added. 添加文件时,它将报告创建事件。 If that file is named "temp" then you can add a watch on that file. 如果该文件名为“ temp”,则可以在该文件上添加监视。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM