我正在使用 inotify 来监听对文件的修改。
当我测试文件修改时,程序运行正常。
# echo "test" > /tftpboot/.TEST
Output:
Read 16 data
IN_MODIFY
但是当我执行 tftp put 时,会生成两个事件:
tftp> put .TEST
Sent 6 bytes in 0.1 seconds
tftp>
Output:
Read 16 data
IN_MODIFY
Read 16 data
IN_MODIFY
知道如何避免重复通知吗?
代码如下:
#include <sys/inotify.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
int fd = inotify_init();
if (fd < 0)
{
cout << "inotify_init failed\n";
return 1;
}
int wd = inotify_add_watch(fd, "/tftpboot/.TEST", IN_MODIFY);
if (wd < 0)
{
cout << "inotify_add_watch failed\n";
return 1;
}
while (true)
{
char buffer[sizeof(struct inotify_event) + NAME_MAX + 1] = {0};
ssize_t length;
do
{
length = read( fd, buffer, sizeof(struct inotify_event));
cout << "Read " << length << " data\n";
}while (length < 0);
if (length < 0)
{
cout << "read failed\n";
return 1;
}
struct inotify_event *event = ( struct inotify_event * ) buffer;
if ( event->mask & IN_ACCESS )
cout << "IN_ACCESS\n";
if ( event->mask & IN_CLOSE_WRITE )
cout << "IN_CLOSE_WRITE\n";
if ( event->mask & IN_CLOSE_NOWRITE )
cout << "IN_CLOSE_NOWRITE\n";
if ( event->mask & IN_MODIFY )
cout << "IN_MODIFY \n";
if ( event->mask & IN_OPEN )
cout << "IN_OPEN\n";
}
inotify_rm_watch( fd, wd );
close (fd);
return 0;
}
尝试使用IN_CLOSE_WRITE
instead
Q: 有什么区别IN_MODIFY and IN_CLOSE_WRITE?
这
IN_MODIFY 事件在文件内容更改时发出(例如通过
write() 系统调用),而 IN_CLOSE_WRITE 发生在关闭更改时
文件。这意味着每个更改操作都会导致一个 IN_MODIFY 事件(它
在使用打开的文件进行操作期间可能会发生多次),而
IN_CLOSE_WRITE 仅发出一次(在关闭文件时)。
Q: 还是用比较好IN_MODIFY or IN_CLOSE_WRITE?
它不同于
个案。通常使用IN_CLOSE_WRITE比较合适
因为如果发出,相应文件上的所有更改都是安全的
写在文件里面。 IN_MODIFY 事件并不一定意味着文件
更改完成(数据可能保留在内存缓冲区中
应用)。另一方面,许多日志和类似文件必须
使用 IN_MODIFY 进行监视 - 在这些文件是的情况下
永久打开,因此不能发出 IN_CLOSE_WRITE。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)