为什么需要使用 inotify_add_watch() 调用 read() 两次
Why is it required to call read() twice with inotify_add_watch()
我正在尝试在文件被修改时使用 inotify_add-watch() 获取通知 (inotify_add_watch (fd, filename.c_str (), IN_MODIFY);) on linux 文件系统(linux kernel 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));
}
}
}
在它再次开始阻塞之前,您必须消耗所有未决事件。
当你例如做echo foo > /etc/test
,你可能会得到两个事件:一个是截断,一个是写。
两个都不消费,下一个会立即返还。
我正在尝试在文件被修改时使用 inotify_add-watch() 获取通知 (inotify_add_watch (fd, filename.c_str (), IN_MODIFY);) on linux 文件系统(linux kernel 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));
}
}
}
在它再次开始阻塞之前,您必须消耗所有未决事件。
当你例如做echo foo > /etc/test
,你可能会得到两个事件:一个是截断,一个是写。
两个都不消费,下一个会立即返还。