Rob van der Woude's Scripting Pages

How to lock single-user programs on a network

Sometimes it may be necessary to use a single user program on a network.
If the program cannot restrict the number of concurrent users itself, the following batch file comes in handy.

Start the batchfile with the current user ID as its first command line parameter (case sensitive!).
The other parameters, starting at %2, are passed to the single user program.

The batch file creates a temporary batch file LOCKED.BAT in the startup directory to signal that the program (or its data, depending on the startup directory) is locked.
So, the first thing it does is check if LOCKED.BAT exists.
If true, it executes it to set the environment variable LOCKEDBY to the user ID of the person who locked the program.
It then checks if that might be he (she) himself (herself), as might be the case when the program wasn't terminated normally.
If it was the user himself (herself) who locked the program, the lock is removed (the batch file LOCKED.BAT is deleted).
After this "crash check" a new LOCKED.BAT is created containing the current user's user ID (%1).
That way, the next users will know who has locked the program.
Next, the program is run.
After a normal termination of the program, LOCKED.BAT is deleted, so the program is available again to others.

If for some reason the person who locked the program is unable to unlock it, delete LOCKED.BAT manually.

Replace MyProg.exe with the executable (path and) file name of your program.

@ECHO OFF
:: Check if program is locked, and by whom
IF EXIST LOCKED.BAT CALL LOCKED.BAT
:: Unlock if it was you yorself who locked it
IF "%LOCKEDBY%"=="%1" DEL LOCKED.BAT
:: Check again if program is locked, and by whom
IF EXIST LOCKED.BAT GOTO Locked
:: Lock it if it isn't locked by someone else
ECHO SET LOCKEDBY=%1>LOCKED.BAT
:: Start the program
:: (the first command line parameter, %1,
:: was used for this locking batch file)
MyProg.exe %2 %3 %4 %5 %6 %7 %8 %9
:: Free the program
SET LOCKEDBY=
DEL LOCKED.BAT
:: And quit
GOTO End

:Locked
CALL LOCKED.BAT
ECHO.
IF "%LOCKEDBY%"=="" GOTO Locked2
ECHO %LOCKEDBY% uses MYPROGRAM right now.
ECHO %LOCKEDBY% can free MYPROGRAM again by closing it normally.
GOTO Errors

:Locked2
ECHO Someone else has locked MYPROGRAM.
ECHO Contact your helpdesk or administrator.

:Errors
ECHO.
PAUSE

:End

 

In Windows NT, you may forget about using the first parameter for the user ID. Instead, replace the line:
IF "%LOCKEDBY%"=="%1" DEL LOCKED.BAT
with:
IF /I "%LOCKEDBY%"=="%USERNAME%" DEL LOCKED.BAT
Of course, you then need to replace the line:
MyProg.exe %2 %3 %4 %5 %6 %7 %8 %9
with:
MyProg.exe %*
as well.

 

Click to view sourceClick to download source

page last modified: 2011-03-04; loaded in 0.0024 seconds