我使用以下代码使用 I notify 来监视文件。我首先轮询然后阅读是否有更改以防止阻塞:
int settingsCheck(int &length, int &i, char * buffer, int &fd, string setRead[])
{
int f_change = 0;
struct pollfd pfd = { fd, POLLIN, 0 };
/* Poll with a timeout of 100ms */
int ret = poll(&pfd, 1, 100);
/* Check to see the result of the poll */
if (ret < 0) {
fprintf(stderr, "Poll failed: %s\n", strerror(errno));
}
else if (ret == 0) {
/* Timeout with no events -> move on */
}
else {
/* Process the new event */
struct inotify_event event;
length = read(fd, buffer, BUF_LEN);
printf("read\n");
while (i < length)
{
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len)
{
if (event->mask & IN_MODIFY && event->name == "setitngs.txt")
{
printf("The file %s was modified.\n", event->name);
//f_change = 1;
}
else if(event->mask & IN_MODIFY)
{
printf("Not settings\n");
}
}
i += EVENT_SIZE + event->len;
}
readSettings(setRead);
return 1;
}
return 0;
}
当我修改被监控的文本文件(由 php 脚本修改)时,我的程序会多次读取文件(2-4 次),有时仅在最终读取时读取正确的数据。
有谁知道为什么会发生这种情况/如何解决?
PS:我说的是正确的,如果我在以下情况下调用 readSettings() 函数:
if (event->mask & IN_MODIFY && event->name == "setitngs.txt")
那么 readSettings() 应该只在“settings.txt”被监控时调用一次?