最近遇到了监控日志文件实时变化的需求,我使用Perl的Linux::Inotify2模块来实现的,简单介绍一下这个模块的使用方法。
比如我们要监控文件被修改事件,捕获到事件后,就创建子进程去执行一些我们需要的操作,这里我给出最基本的代码。
#!/usr/bin/perl -w
use strict;
use Linux::Inotify2;
my $logFile = '/var/log/xxx.log';
my $inotify = Linux::Inotify2->new()
or die "Unable to create new inotify object:$!";
$inotify->watch($logFile,IN_MODIFY)
or die "Unable to watch the file:$!";
while(){
my @events = $inotify->read;
unless(@events > 0){
print "Read data error:$!";
last;
}
my $child = fork();
die "Cannot fork:$!" unless defined $child;
if(!$child){
&youWantToDo("Attention,$logFile was modified!");
exit 0;
} else {
wait;
}
}
sub youWantToDo{
my $msg = shift;
print $msg . "n";
}
如果你需要监控别的事件或者要知道Linux::Inotify2的详细用法,去CPAN的官方阅读该模块的帮助文档。
转载请注明:爱开源 » Inotify文件监控