Perl inotify2 triggers twice for each file modification

I am writing a Perl script that monitors a file for changes.

#!/usr/bin/perl
use strict;
use Linux::Inotify2;

my $inotify = new Linux::Inotify2 or die $!;
my $filename = "/tmp/foo";
my $counter = 0;

$inotify->watch (
    $filename,
    IN_MODIFY,
    sub {
        ++$counter;
        print "changed: $counter\n";
    }
) or die $!;

1 while $inotify->poll;

This handler is called twice (incrementing $ counter twice) every time / tmp / foo changes if I test it like this:

echo abc > /tmp/foo

Why?

+4
source share
2 answers

Use either >>, as @Lajos Veres suggested, or watch the event CLOSE_WRITE( IN_CLOSE_WRITE for the module Linux::Inotify2).,

echo > /tmp/foo

inotifywait -m /tmp/foo
Setting up watches.
Watches established.
/tmp/foo MODIFY
/tmp/foo OPEN
/tmp/foo MODIFY
/tmp/foo CLOSE_WRITE,CLOSE
+4
source

> truncates the file first (I think this is also the modification itself). Try using →.

+4
source

All Articles