2013-05-24 2 views
2

디렉터리에서 변경 내용을 수신 대기하는 코드가 있습니다. 실행하면 파일에 아무 것도 쓰지 않고 터미널에 출력되지 않습니다.dir 또는 파일의 변경 사항을 수신하는 방법은 무엇입니까?

특정 텍스트 파일에서 변경 사항을 수신 대기하는 사람이 있습니까? 타임 스탬프를 저장하고 변경 사항을 저장하려고합니다.

코드는 다음과 같습니다

/*This is the sample program to notify us for the file creation and file deletion takes place in “/tmp” directory*/ 
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <sys/types.h> 
#include <linux/inotify.h> 

#define EVENT_SIZE (sizeof (struct inotify_event)) 
#define EVENT_BUF_LEN  (1024 * (EVENT_SIZE + 16)) 

int main() 
{ 
    int length, i = 0; 
    int fd; 
    int wd; 
    char buffer[EVENT_BUF_LEN]; 
    char str[] = "This is tutorialspoint.com"; 
    FILE* fp=NULL;; 
    fp=fopen("f1.txt","rw+"); 

    /*creating the INOTIFY instance*/ 
    fd = inotify_init(); 

    /*checking for error*/ 
    if (fd < 0) { 
    perror("inotify_init"); 
    } 

    /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/ 
    wd = inotify_add_watch(fd, "/tmp", IN_CREATE | IN_DELETE); 

    /*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/ 

    length = read(fd, buffer, EVENT_BUF_LEN); 

    /*checking for error*/ 
    if (length < 0) { 
    perror("read"); 
    } 

    /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/ 
    while (i < length) {  struct inotify_event *event = (struct inotify_event *) &buffer[ i ];  if (event->len) { 
     if (event->mask & IN_CREATE) { 
     if (event->mask & IN_ISDIR) { 
      printf("New directory %s created.1\n", event->name); 
     fwrite(str , 1 , sizeof(str) , fd); 
     } 
     else { 
      printf("New file %s created.\n2", event->name); 
     fwrite(str , 1 , sizeof(str) , fd); 
     } 
     } 
     else if (event->mask & IN_DELETE) { 
     if (event->mask & IN_ISDIR) { 
      fwrite(str , 1 , sizeof(str) , fd); 
      printf("Directory %s deleted.\n", event->name); 
     } 
     else { 
      printf("File %s deleted.\n", event->name); 
     } 
     } 
    } 
    i += EVENT_SIZE + event->len; 
    } 
    /*removing the “/tmp” directory from the watch list.*/ 
    inotify_rm_watch(fd, wd); 
    fclose(fd); 
    /*closing the INOTIFY instance*/ 
    close(fd); 

} 

답변

1

내 생각 엔 인 read 전화에 단순히 블록이. 위의 코멘트에서 : 변경 이벤트는 단순히이

발생 당신이 기다리고있는 이벤트 중 하나를 발생되지 않으며,이 read 호출 할 때까지 차단됩니다 때까지

사실이 블록을 읽어 거기있다.

이 프로그램을 한 터미널에서 실행하고 다른 터미널에서 실행하는 것이 좋습니다.

$ touch /tmp/foo 
+1

답장을 보내 주셔서 감사합니다. –

+0

@ user2134703 디버거에서 프로그램을 실행하고 한 줄씩 단계별로 실행하는 것이 좋습니다. 그러면 무슨 일이 일어나는지보고, 변수의 값을 확인할 수 있습니다. –

+0

아, 죄송합니다. 터미널에서 생성되거나 삭제 된 파일을 보여줍니다. 하지만 단 한 번의 조작 만 가능합니다. 여러 작업을 듣기 위해 수행해야 할 작업은 무엇입니까? nohup ./a와 같이 작동하며 작동합니까? –