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

I have a project that I need to monitor a batch file that constantly works, to check if everything works. I have a remote machine that needs to control this batch file running on another server.

I need to make the batch file create and block only a text file (it may be empty, it may be complete, it does not matter). This means that I can interrogate it from my remote machine (using exe created by C #) to see if there is an exclusive file lock - if so, do nothing. If you can get a lock, then raise an alarm (as the batch fails).

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

+4
source share
2 answers

At first I was skeptical about this, but it turns out that this can be done 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

While the running batch is running, it is not possible to remove lockfile.txt.

Essentially, batch checking for the '-lock' parameter. If it is absent, it re-executes itself with the -lock option and redirects its own output to the lockfile.txt file

It is also possible to create locks for β€œcritical” partitions within a batch, for example.

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

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

echo %DATE% %TIME% - finished

Sources:

Windows?

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

+7

, . txt .

@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')"

.

+1

All Articles