#!/usr/bin/perl -w $|=1; ## Don't buffer output use CGI; use Fcntl qw(:flock); my $file = 'tmp/test_lock.txt'; my $SEMAPHORE = $file . '.lck'; # Output Early for debug my $q = new CGI; print $q->header; my $x; for ($x = 0; $x < 50; $x++) { print "\n"; } for ($x = 0; $x < 10; $x++) { print "Line $x
\n"; sleep 1; } print "Getting lock
\n"; open(S, ">$SEMAPHORE") or die "$SEMAPHORE: $!"; flock(S, LOCK_EX) or die "flock() failed for $SEMAPHORE: $!"; print "Got lock
\n"; my $l; my @in; if (open (FH, "$file")) { @in = ; close FH; foreach $_ (@in) { if ($_ =~ /(.*): I have/) { $l = $1; } } $l = $l+1 if $l; } else { print "Can't open $file: $!"; } $l = 1 unless $l; push (@in,"$l: I have written ($$) flock\n"); open (FH, ">$file") or die "Can't open $file: $!"; print "About to write
\n"; print FH @in; print "Written: $l
\n"; close FH; print "Going to sleep...\n"; for ($x = 0; $x < 50; $x++) { print "$x ...
\n"; sleep 1; } print "Woken up...
\n"; close S;