2014-07-08 79 views
2

我需要注意基於Unix系統上文件的修改,並且我無法訪問Boost。我想知道下面的邏輯是否正確。我認爲這可能是低效率的,而且我知道我在while循環中根本沒有睡覺而浪費了大量的週期,但是我沒有估計文件在修改之間需要多長時間,我需要知道相對較快:比較文件統計時間

std::time_t getTimeLastModified(const char* filename){ 

    struct stat fileattrib; 
    stat(filename, &fileattrib); 

    return fileattrib.st_mtime; 
} 

int main(){ 

    std::time_t file1_modified_time = getTimeLastModified(coor_file.c_str()); 

    while(difftime(getTimeLastModified(coor_file.c_str()),file1_modified_time)==0){} 

    // If program execution gets here, file has been modified 
} 
+3

爲什麼不使用'inotify'如果你的內核可用? –

+0

inotify在我工作的生產系統上不可用。我無法在此係統上重新編譯內核,也無法在系統上進行root訪問。 – cooper

回答

3

用於檢查mod時間的邏輯主要是聲音。

您只需要錯誤檢查統計返回值 - 以防文件丟失。

struct stat fileattrib; 
int status = stat(filename, &fileattrib); // Get file stats 
if (status < 0) 
    return((std::time_t)-1); // File missing? 
return(fileattrib.st_mtime); 

這將意味着你應該錯誤檢查getTimeLastModified()返回 值。

如果您碰巧知道需要多長時間來輪詢修改文件 修改時間,可以在 while循環中調用usleep(unsinged long usec)。你能做這樣的事嗎?

const unsigned long polltime = 5000; // 5ms 
usleep(polltime); 

要考慮的另一件事是是否超時。也就是說,如果文件永不改變 - 例如10分鐘(或600000000微秒),你會怎麼做 。