开发者

How check if file have been changed via other process?

I have two processes (firsts source in perl, seconds source in c++) and both of them use same file. One of them writes to the file line by line, and another reads from file if new line is appended to it. For second开发者_开发知识库 process to know that file is modified the first proces flush - es after each apendence. But second process checks only modification time to be increased to start read, but actualy after adding new line and flushing the file doesn't change its "last modification time". So there is another aporache is needed to do this. So the question is here, how detect if new line is appended to the file, to start its processing?

here are fragments from source codes of this proceses:

1.

open FILE, ">>", $file or die $!;
for($i = 0; $i <= $#ticks; ++$i)
{
  print FILE $ticks[$i]."\n";
  FILE->flush();
  sleep(10);
}
close FILE;

2.

struct stat64 file_info;
if(fstat64(fileno(this->auto_file_ptr.get_file()), &file_info)!=0)
{
//throw error that file have been changed
}
data_file_new_modification_time = 1000LL * file_info.st_mtime;
if(this->data_file_last_modification_time!=data_file_new_modification_time)
{
//processs the file
}


Use IPC mechanisms to synchronize you C++ and Perl application. You can use semaphores or mutexes for this purpose.


Welcome to event-based programming.

Employ select - you do not want to know when the file is changed, but when new data is available. This system call does exactly that.

See the implementation in File::Tail for a real-world example with all the edge cases nicely grated off. Downporting this to C should be easy for you, or use libev with the select backend.


It seems that stat64 doesn't change it's st_mtime member when file is flushed. Instead the st_size changes. So I can use st_size to detect if file was changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜