2012-02-01 7 views
1

나는 우분투에서 일하고있다. 하위 폴더 (인쇄 파일)에서 팝업되는 모든 이벤트를 폴더를 모니터링하고 인쇄하려고합니다. 다음 코드가 있지만 작동하지 않습니다. 실행될 때 이벤트의 println이 없습니다.이벤트에 대한 inotify 및 인쇄에 반응하는 프로그램

두 번째 코드에서 나는 폴더의 이벤트 만 볼 수 있습니다. 각 하위 폴더의 이벤트가 팝업되지 않습니다.

#include <string> 
#include <iostream> 
#include <stdio.h> 
using namespace std; 
std::string exec(char* cmd) { 
    FILE* pipe = popen(cmd, "r"); 
    if (!pipe) return "ERROR"; 
    char buffer[256]; 
    std::string result = ""; 
    while(!feof(pipe)) { 
     if(fgets(buffer, 256, pipe) != NULL) 
       result += buffer; 
    } 
    pclose(pipe); 
    cout<<"result is: "<<result<<endl; 
    return result; 
} 

int main() 
{ 
    //while(1) 
    //{ 
    string s=exec((char*)"inotifywait -rme create /home/folder/"); 

    cout << s << endl; 
    //} 
    return 0; 
} 

이 코드는 모니터링하는 폴더의 이벤트 만 인쇄합니다. 각 하위 폴더의 이벤트는 인쇄되지 않습니다. 나는 나의 필요를 위해 그것을 향상시키는 방법을 모른다.

#include <sys/inotify.h> 
#include <sys/ioctl.h> 
#include <iostream> 

void processNewFiles(int fd, int wd); 


int main(int argc, char** argv) 
{ 
    const char* dirPath = "/home/folder/" ;//argv[1]; 

    int fd = inotify_init(); 
    int wd = inotify_add_watch(fd, dirPath, IN_CREATE); 

    if (wd) 
    { 
     processNewFiles(fd, wd); 

     inotify_rm_watch(fd, wd); 
    } 
} 


void processNewFiles(int fd, int wd) 
{ 
    bool done = false; 

    do 
    { 
     int qLen = 0; 

     ioctl(fd, FIONREAD, &qLen); 

     char* buf = new char[qLen]; 
     int num = read(fd, buf, qLen); 

     if (num == qLen) 
     { 
     inotify_event* iev = reinterpret_cast<inotify_event*>(buf); 

     if (iev->wd == wd && iev->mask & IN_CREATE) 
     { 
      std::cout << "New file created: " << iev->name << std::endl; 
     } 
     } 

     delete [] buf; 
    } while (!done); 
} 
+1

* * 어떤 코드가 작동하지 않습니까? – Xeo

+0

g ++ 코드로 실행 중입니다. 문자열 s에 대한 출력이 없습니다. –

답변

1

inotify_add_watch가 반복적으로 작동하지 않기 때문에 두 번째 해결책이 작동하지 않습니다. 하위 디렉토리에 대한 시계를 수동으로 추가해야합니다. 이것이 귀찮을 수도 있으므로 첫 번째 예제에서와 같이 유틸리티 inotifywait을 사용할 수도 있습니다.

파이프에서 영원히 읽음으로써 첫 번째 예가 작동하지 않습니다. inotifywait 프로세스를 죽이는 경우 (예 : 시스템의 유일한 사람이고 "killall inotifywait"을 사용하는 유일한 inotifywait 프로세스 인 경우) 파이프에서 루프를 읽는 중 끊어 지므로 출력을 얻습니다 . 루프 내부에 무언가를 출력하면 작동합니다.

관련 문제