【问题标题】:Monitoring file changes using select() within a loop在循环中使用 select() 监视文件更改
【发布时间】:2020-12-18 00:24:03
【问题描述】:

我正在尝试编写一个程序,该程序将不断跟踪文件中的更改并相应地执行一些操作。我在循环中使用 inotify 和 select 以非阻塞方式跟踪文件修改。我的程序的文件跟踪部分的基本结构如下。

#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 Changed\n");
    } 

}

我检查了选择手册页并在每次 select() 返回时重置 fd_set 描述符。但是,每当我修改文件 (input.txt) 时,这段代码就会无限循环。我使用 inotify 和 select 的经验不是很丰富,所以,我确定问题是否出在我使用 inotify 或 select 的方式上。我将不胜感激任何提示和建议。

【问题讨论】:

    标签: linux select inotify file-monitoring


    【解决方案1】:

    您必须在选择返回后读取缓冲区的内容。如果 select() 在缓冲区中找到数据,则返回。因此,对该文件描述符(inotfd)执行 read()。 read 调用读取数据并返回它读取的字节数。现在,缓冲区是空的,在下一次迭代中,select() 调用会一直等待,直到缓冲区中有可用的数据。

    while(1)
    {
    // ...
        char pBuf[1024];
        res=select(FD_SETSIZE,&rfds,NULL,NULL,&timeout);
        read(inotfd,&pBuf, BUF_SIZE);
    // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      相关资源
      最近更新 更多