Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 499
user3266154 Avatar asked Aug 04 '14 14:08

user3266154


People also ask

How do I lock a batch file?

Navigate to where you saved the batch file in File Explorer. Double-click the batch file to run it. This will create a new folder called "Locker" in the same folder as the batch file. Move all the things you want to hide into the Locker folder.


2 Answers

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

like image 115
andyb Avatar answered Oct 19 '22 04:10

andyb


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.

like image 25
Knuckle-Dragger Avatar answered Oct 19 '22 03:10

Knuckle-Dragger