使用perl(macos和linux)查看文件以进行更改

时间:2017-06-04 00:38:42

标签: watch inotify

我想看一组文件进行更改,并且这样做没有大的CPU和电池损失。理想情况下,我的perl代码可以在macos和linux上运行,但前者更重要。我试过了

我尝试了Mac::FSEvents,它可以在macos上工作,对于目录来说似乎做得很好,但据我所知,文件并不适用。

my $fs = Mac::FSEvents->new('try.txt');
my $fh= $fs->watch;

my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}

根本没有回应;和有希望的更多操作系统不可知

use File::Monitor;
my $monitor = File::Monitor->new();

my @files= qw(try.txt);

foreach (@files) { $monitor->watch($_); }

消耗100%的CPU。仅$monitor-watch()不会阻止。我也试过

use File::Monitor;
my $monitor = File::Monitor->new();

$monitor->watch('try.txt', sub {
                  my ($name, $event, $change) = @_;
                  print "file has changed\n";
                });

但这会立即返回。

我找到了另一个,

use File::ChangeNotify;

my $watcher =
  File::ChangeNotify->instantiate_watcher
  ( directories => [ './' ],
    filter      => qr/try\.txt/,
  );

# blocking
while ( my @events = $watcher->wait_for_events() ) {
  print "file has changed\n";
}

但CPU利用率再次高(70%)。

也许这些都是错误的cpan模块。有人可以就如何做到这一点给我建议吗?

的问候,

/ IAW

1 个答案:

答案 0 :(得分:0)

部分(特定于macos)示例:

use IO::Select;
use Mac::FSEvents;
my $fs = Mac::FSEvents->new(
    path          => ['./try.txt', './try2.txt'],
    file_events   => 1,
    );

my $fh= $fs->watch;
my $sel = IO::Select->new($fh);
while ( $sel->can_read ) {
  my @events = $fs->read_events;
  for my $event ( @events ) {
    printf "File %s changed\n", $event->path;
  }
}

(即,它需要file_events标志。)