in reply to mutual exclusion and file locking on windows

Perhaps the easiest way to prevent multiple instance of a CGI from running would be to write a semaphore file when the script first executes. The script checks if this semaphore exists and refuses to run if it does - instead it returns a "Busy, try later" message to the browser. Once the script has finished it deletes the sempahore file and exits opening the way for further instances of the script to have at it.

use strict; use Fcntl qw(:DEFAULT); my $semaphore = 'c:/test.txt'; sysopen (SEMAPHORE, $semaphore, O_WRONLY | O_EXCL | O_CREAT) or &busy; print "There can be only one!"; sleep 20; close SEMAPHORE; unlink $semaphore or die "Can't unlink $semaphore $!\n"; exit; sub busy { print "Sorry, I am busy!"; exit; }

The sysopen opens a file for writing (O_WRONLY); fails if the file already exists (O_EXCL) and creates a file if it does not exist (O_CREAT). It does this all in one step which help avoid race conditions. If this fails we do our busy sub. If it succeeds when the script finishes it unlinks the file so another instance of this script can run.

While flock may work on some versions of Windows under 95/98 using Active State build 621 here is what happens:

C:\>type flock.pl use Fcntl qw(:flock); print "This is $^O\n"; open FILE, ">>test.txt" or die "Oops $!\n"; flock FILE, LOCK_EX or die "Can't flock $!\n"; close FILE; C:\>perl flock.pl This is MSWin32 flock() unimplemented on this platform at flock.pl line 6. C:\>

I am interested to know which versions of Win32 flock works under as it is clearly not all.

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re: Re: mutual exclusion and file locking on windows
by fredt (Novice) on Aug 07, 2001 at 21:50 UTC
    It must be that flock works only on NT and Windows 2000. I tried your flock code and got the same failure on a Windows 98 machine, but it ran without error on a Windows 2000 server machine (ActiveState 626). Thanks for your help.

      No worries. I posted a question at Flock 'n Windows if you want to see all the systems that don't support flock. Using a semaphore is the workaround.

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print