5

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?

andyb
  • 2,722
  • 1
  • 18
  • 17
user3266154
  • 49
  • 1
  • 6
  • Plain vanilla CMD statements don't have file locking capability. To get a solution you'd need to discuss your server batch file. – foxidrive Aug 04 '14 at 16:45
  • Agree with @foxidrive - more details of server batch file needed. Does it run in a continuous loop? If so, how frequently? Does it execute long running external commands? I don't think its possible for a batch to maintain a lock on a file - this is not the nature of batch processing. It could write frequent messages to a log though and these could be monitored. Alternatively (and better), use WMI to confirm the process is still alive. – andyb Aug 05 '14 at 03:13

2 Answers2

11

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

Community
  • 1
  • 1
andyb
  • 2,722
  • 1
  • 18
  • 17
1

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.

Knuckle-Dragger
  • 6,644
  • 4
  • 26
  • 41