【问题标题】:watching files for changes with perl (macos and linux)使用 perl (macos 和 linux) 监视文件的更改
【发布时间】:2017-06-04 00:38:41
【问题描述】:

我想查看一组文件是否有更改,这样做不会消耗大量 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

【问题讨论】:

    标签: watch inotify


    【解决方案1】:

    部分(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 标志。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2011-06-18
      相关资源
      最近更新 更多