Linux :: Inotify2和线程

时间:2018-02-02 19:44:24

标签: multithreading perl inotify

我尝试使用Linxu :: Inotify2 - 但不是在线程中。

如果我在程序中有线程,那么我会在Inotifys读取时崩溃。 如果我不使用线程,一切都很好。

这是一个应该显示问题的小样本。

use strict;
use warnings;
use threads;
use Linux::Inotify2;

my $X = 0;  # terminate the thread: 0=nothing, 1=detach, 2=join

STDOUT->autoflush ();
my $ino = new Linux::Inotify2 ();

$ino->blocking (0);
$ino->watch (".", IN_MODIFY | IN_ATTRIB | IN_CREATE) or die "error";

my @ls = ();   # for save threads if $X == 2
for (my $i=0;;$i++)
{
    my $th = threads->create (sub { print "\nTH". shift; }, $i);  # just to have threads; do nothing
    if ($X == 1)
    {
        $th->detach ();     # detach the thread
    }
    elsif ($X == 2)
    {
        push (@ls, $th);    # save for joining after thread finished
    }

    my @events = $ino->read ();   # *** CRASH if $X = 1 or 2
    if ($X == 2)
    {
        foreach (@ls)
        {
            if ($_->is_joinable ())
            {
                $_->join ();
            }
        }
    }

    sleep (1);
}

如果我将$ X设置为0,它将起作用。 如果我将其设置为1或2,那么我会收到运行时错误。

Linux::Inotify2: read error while reading events at /usr/local/lib/x86_64-linux-gnu/perl/5.26.0/Linux/Inotify2.pm line 266.

为什么?

修改

我简化了我的示例,以便更好地了解问题。

use strict;
use warnings;
use threads;
use Linux::Inotify2;

STDOUT->autoflush ();
my $ino = new Linux::Inotify2 ();

$ino->blocking (0);
$ino->watch (".", IN_CREATE | IN_DELETE) or die "error";

my $th = threads->create (sub {  });
$th->join ();

print "\nINO: ".$ino->poll();

删除连接即可,保留连接并且轮询将失败。

1 个答案:

答案 0 :(得分:1)

以下示例实现了zdim的想法,他建议使用带有poll()而不是read()的事件循环。它是在CentOS 7上使用Perl 5.16.2和Linux-Inotify2 v1.22开发的。

该程序产生一个监视/tmp目录的线程。您可以通过触摸和删除文件来测试它:touch /tmp/1 /tmp/2 && rm /tmp/1 /tmp/2

#!/usr/bin/env perl

use warnings FATAL => 'all';
use strict;
use threads;

threads->new(\&_eventListener, '/tmp')->join();

sub _eventListener {
  my ($path) = @_;

  require Linux::Inotify2;
  Linux::Inotify2->import(qw(IN_CREATE IN_DELETE IN_DELETE_SELF));

  my $fsEventListener = Linux::Inotify2->new() or 
    die('Cannot register Linux::Inotify2, stopped');

  $fsEventListener->watch(
    $path, 
    IN_CREATE() | IN_DELETE() | IN_DELETE_SELF(), 
    \&_watchCallback
  ) or die("Watch creation failed. '$!'");

  $fsEventListener->blocking(undef);

  while(1) {
    $fsEventListener->poll();
    sleep 1;
  }

  return;
}

sub _watchCallback {
  my ($e) = @_;

  printf STDOUT "Receive event '0x%04x' for file '%s'\n", $e->mask(), $e->fullname();

  return;
}