2014-11-25 1 views
0

파일의 변경 사항을 지속적으로 추적하고 그에 따라 몇 가지 작업을 수행하는 프로그램을 작성하려고합니다. 나는 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()가 돌아올 때마다 select 설명서 페이지를 확인하고 fd_set 디스크립터를 재설정했습니다. 그러나 파일 (input.txt)을 수정할 때마다이 코드는 무한 루프 만 수행합니다. 나는 inotify와 select를 사용하는 것에 경험이별로 없기 때문에 문제가 Inotify를 사용하거나 선택하는 방법과 관련이 있다면 확신한다. 나는 힌트와 recommentations을 주셔서 감사합니다.

답변

2

선택이 반환 된 후에 버퍼의 내용을 읽어야합니다. select()가 버퍼에서 데이터를 찾으면 리턴합니다. 그래서, 그 파일 기술자 (inotfd)에 대해 read()를 수행하십시오. read 호출은 데이터를 읽고 읽은 바이트 수를 반환합니다. 이제 버퍼가 비어 있고 다음 반복에서 select() 호출은 버퍼에서 데이터를 사용할 수있을 때까지 대기합니다.

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