我正在尝试编写一个程序,该程序将不断跟踪文件中的更改并相应地执行多项操作。我正在使用inotify并在循环中选择以非阻塞方式跟踪文件修改。我的程序的文件跟踪部分的基本结构如下。
#include <cstdio>
#include <signal.h>
#include <limits.h>
#include <sys/inotify.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <string>
int main( int argc, char **argv )
{
const char *filename = "input.txt";
int inotfd = inotify_init();
char buffer[1];
int watch_desc = inotify_add_watch(inotfd, filename, IN_MODIFY);
size_t bufsiz = sizeof(struct inotify_event) + 1;
struct inotify_event* event = ( struct inotify_event * ) &buffer[0];
fd_set rfds;
FD_ZERO (&rfds);
struct timeval timeout;
while(1)
{
/*select() intitialisation.*/
FD_SET(inotfd,&rfds); //keyboard to be listened
timeout.tv_sec = 10;
timeout.tv_usec = 0;
int res=select(FD_SETSIZE,&rfds,NULL,NULL,&timeout);
FD_ZERO(&rfds);
printf("File Changedn");
}
}
我检查了选择手册页,并在每次 select() 返回时重置fd_set描述符。但是,每当我修改文件(input.txt)时,此代码都会无限循环。我使用inotify and select不是很有经验,所以,我确定问题是否出在我使用inotify or select的方式上。我将不胜感激任何提示和评论。
选择返回后读取缓冲区的内容。 如果 select() 在缓冲区中找到数据,它将返回。 因此,对该文件描述符 (inotfd) 执行 read()。 read 调用读取数据并返回它读取的字节数。 现在,缓冲区为空,在下一次迭代中,select() 调用将等待缓冲区中的任何数据可用。
while(1)
{
// ...
char pBuf[1024];
res=select(FD_SETSIZE,&rfds,NULL,NULL,&timeout);
read(inotfd,&pBuf, BUF_SIZE);
// ...
}