【发布时间】:2018-08-17 20:45:34
【问题描述】:
我正在尝试在文件被修改时使用 inotify_add-watch() 获取通知 (inotify_add_watch (fd, filename.c_str(), IN_MODIFY);) 在 linux 文件系统上(linux 内核 4.9.0)。
但在收到通知后,预计 read() 会调用两次,直到我收到有关文件 /etc/temp 的下一次修改的通知。有人可以澄清为什么我需要两次调用 read() 吗?谢谢。
int fd, wd;
fd = inotify_init ();
if (fd < 0)
{
perror ("inotify_init () = ");
}
else
{
std::string filename = "/etc/test";
wd = inotify_add_watch (fd, filename.c_str(), IN_MODIFY);
if (wd < 0)
{
perror ("inotify_add_watch");
}
else
{
char* buffer = new char[1024];
while(true)
{
//first read blocks until the /etc/temp file is modified,
//it returns 16 which is sizeof(struct inotify_event)
printf("first read %d), read( fd, buffer, 1024));
//second read() does not block and read returns 16 again
printf("second read %d), read( fd, buffer, 1024));
}
}
}
【问题讨论】: