user3266154
user3266154

Reputation: 49

How to get an exclusive lock on a file using batch file?

I have a project I need to monitor a batch file which constantly runs to see if its still working. I have a remote machine which needs to monitor this batch file running on another server.

What i need to do is have the batch file create and exclusively lock a text file (can be empty, can be full it does not matter). This is so I can poll it from my remote machine (using an exe created by c#) to see if there is exclusive lock on the file - if so, then do nothing. If can get a lock, then raise alarm (as the batch has failed).

Understand this is probably not the best approach, but unfortunately its what I have to go with. So, is there a way to exclusively lock a file (automatically) using a batch file?

Upvotes: 5

Views: 8585

Answers (2)

andyb
andyb

Reputation: 2772

I was skeptical about this initially, but it turns out it can be done by using file redirection. Consider this example:

@echo off

if '%1' == '-lock' (
    shift
    goto :main
)
call %0 -lock > lockfile.txt
goto :eof

:main
echo %DATE% %TIME% - start
TREE C:\
echo %DATE% %TIME% - finish
goto :eof

Whilst the above batch is running, it is not possible to delete lockfile.txt.

Essentially, the batch checks for a '-lock' parameter. If it's not present, it re-executes itself with the -lock parameter and re-directs it's own output to lockfile.txt

It's also possible to create locks for 'critical' sections within a batch e.g.

@echo off
echo %DATE% %TIME% - started

(
    echo Starting TREE
    tree c:\
    echo TREE finished
    ) > lock2.lock

echo %DATE% %TIME% - finished

Sources:

How do you have shared log files under Windows?

http://www.dostips.com/forum/viewtopic.php?p=12454

Upvotes: 11

Knuckle-Dragger
Knuckle-Dragger

Reputation: 7046

Here is a plain vanilla batch file to lock a particular file temporarily. Edit the txt path accordingly.

@ECHO OFF
powershell.exe -command "$lock=[System.IO.File]::Open('C:\test.txt','Open','ReadWrite','None');Write-Host -NoNewLine 'Press any key to release the file...';$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')"

It unlocks when you press the any key.

Upvotes: 1

Related Questions