Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl inotify2 triggers twice for each file modification

I am writing a Perl script which 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) each time /tmp/foo changes if I test it like this:

echo abc > /tmp/foo

Why?

like image 445
spraff Avatar asked Feb 16 '23 02:02

spraff


2 Answers

Either use >> as @Lajos Veres suggested, or watch on CLOSE_WRITE event (that is IN_CLOSE_WRITE for Linux::Inotify2 module),

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
like image 128
mpapec Avatar answered Feb 27 '23 12:02

mpapec


The > truncates first the file (I think it is a modification itself also). Try with >>.

like image 37
Lajos Veres Avatar answered Feb 27 '23 10:02

Lajos Veres