Paul Maddox

Software development team leader specialising in Microsoft Visual C# and C++ from the Northwest of England. Experience working in a globalised business and team; understanding of enterprise business operation and practices; experience reporting to executive management Skills in numerous languages and technologies; knowledge of formal software development lifecycle; experience of architecture design

Saturday, March 24, 2007

Pevent duplicate script execution with a lock / critical section

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%

0 Comments:

Post a Comment

<< Home