Saturday, March 24, 2007

Pevent duplicate script execution with a lock / critical section  [Digg.com This!]

Recently I wanted to prevent a batch script from being executed multiple times concurrently. Functionality to prevent this is pretty easy. We can create a file as a lock and check for its existance. If the file exists we know the script is running. By deleting the file at the end of the script we allow other script instances to start.

Here's some sample code:


@echo off

SET LOCK=.%0.lock

if exist %LOCK% (
echo Script is locked
pause
goto :EOF
)

echo > %LOCK%

echo In main program
echo In main program
echo In main program
echo In main program
echo In main program
echo In main program
echo In main program
echo In main program
pause

del %LOCK%