http://www.perlmonks.org?node_id=949042


in reply to [Solved]Easiest way to protect process from duplication.

use Fcntl ':flock'; open my $fh, "+<", $0 or exit; exit unless flock $0, LOCK_EX | LOCK_NB;
Note that depending on your OS and how you call the program, a second open may fail (and then, the flock isn't necessary).

Replies are listed 'Best First'.
Re^2: Easiest way to protect process from duplication.
by gnosti (Chaplain) on Jan 23, 2012 at 05:52 UTC
    Here's a variation that uses the __DATA__ handle.
    use Fcntl qw(LOCK_EX LOCK_NB); die "Another instance is already running" unless flock DATA, LOCK_EX|L +OCK_NB;
      That actually requires a __DATA__ (or __END__) token to be present.
        Thank you too. BTW __END__,__DATA__,etc is there any general name for these tokens, (like "Labeled blocks", "builtins",...)? I'm newbie in perl so I just wanted to read about this stuff.
      Thank you for your post, that is what I really need.
Re^2: Easiest way to protect process from duplication.
by kazak (Beadle) on Jan 21, 2012 at 06:16 UTC
    Thanks for your attention, everyone. Program supposed to run in a background. (I mean # test.pl &) so is it changing something ?
      No, why should it?