等待文件更新然后在 Perl 中读取它的好方法是什么? [英] What is a good way to wait until a file updated and then read from it in Perl?

查看:43
本文介绍了等待文件更新然后在 Perl 中读取它的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以等待文件更新,然后在更新后从中读取.所以如果我有 file.txt,我想等到有新的东西写入它,然后读取它/处理它/等等.目前我正在使用 Time::HiRes::sleep(.01) 进行轮询,但我想知道是否有更好的方法.谢谢.

I was wondering if there's a way to wait for a file to be updated, and then read from it once it's updated. So if I have file.txt, I want to wait until something new is written to it, and then read it/process it/etc. Currently I am polling using Time::HiRes::sleep(.01), but I'm wondering if there's a better way. Thanks.

推荐答案

是的,有更好的方法.在 Windows 上,您可以使用 FileSystemWatcher 界面,在 Linux 上,使用 inotify.

Yes there is a better way. On windows you can use the FileSystemWatcher interface, on Linux, use inotify.

视窗

use Win32::FileSystem::Watcher;

my $watcher = Win32::FileSystem::Watcher->new( "c:\\" );

# or

my $watcher = Win32::FileSystem::Watcher->new(
    "c:\\",
    notify_filter  => FILE_NOTIFY_ALL,
    watch_sub_tree => 1,
);

$watcher->start();
print "Monitoring started.";

sleep(5);

# Get a list of changes since start().
my @entries = $watcher->get_results();

# Get a list of changes since the last get_results()
@entries = $watcher->get_results();

# ... repeat as needed ...

$watcher->stop(); # or undef $watcher

foreach my $entry (@entries) {
    print $entry->action_name . " " . $entry->file_name . "\n";
}

# Restart monitoring

# $watcher->start();
# ...
# $watcher->stop();

Linux

use Linux::Inotify2;
my $inotify = new Linux::Inotify2();

foreach (@ARGV)
{
  $inotify->watch($_, IN_ALL_EVENTS);
}

while (1)
{
  # By default this will block until something is read
  my @events = $inotify->read();
  if (scalar(@events)==0)
  {
    print "read error: $!";
    last;
  }

  foreach (@events)
  {
    printf "File: %s; Mask: %d\n", $_->fullname, $_->mask;
  }
}

这篇关于等待文件更新然后在 Perl 中读取它的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆