简体   繁体   English

如何使用批处理文件获取文件的独占锁定?

[英]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. 这是我可以从我的远程机器(使用由c#创建的exe)轮询它以查看文件是否有独占锁 - 如果是,则不执行任何操作。 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? 那么,有没有办法使用批处理文件独占锁定文件?

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. 上述批处理正在运行时,无法删除lockfile.txt。

Essentially, the batch checks for a '-lock' parameter. 基本上,批处理检查'-lock'参数。 If it's not present, it re-executes itself with the -lock parameter and re-directs it's own output to lockfile.txt 如果它不存在,它将使用-lock参数重新执行自身并将其自己的输出重定向到lockfile.txt

It's also possible to create locks for 'critical' sections within a batch eg 也可以为批次中的“关键”部分创建锁定,例如

@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? 你如何在Windows下共享日志文件?

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

Here is a plain vanilla batch file to lock a particular file temporarily. 这是一个简单的vanilla批处理文件,用于临时锁定特定文件。 Edit the txt path accordingly. 相应地编辑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')"

It unlocks when you press the any key. 当您按任意键时它会解锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM