Home > Articles

  • Print
  • + Share This
From the author of

Locking Demonstrated

This simple script will show you flock() in action. Copy it to your server and run it simultaniously in different consoles. You will see how one will wait for another to finish before obtaining a lock.

        01: #!/usr/bin/perl -wT
        02: use Fcntl qw(:flock);
        03: my $file = 'test_lock.txt';
        04: my $SEMAPHORE = $file . '.lck';
        05: open(S, ">$SEMAPHORE") or die "$SEMAPHORE: $!";
        06: flock(S, LOCK_EX) or die "flock() failed for $SEMAPHORE: $!";
        07: open (FH, ">>$file") or die "Can't open $file: $!";
        08: print "About to write\n";
        09: print FH "I have written ($$)\n";
        10: print "Written\n";
        11: close FH;
        12: print "Going to sleep...\n";
        13: sleep 10;
        14: print "Woken up...\n";
        15: close S;
  • + Share This
  • 🔖 Save To Your Account