简体   繁体   English

如何使用Windows批处理脚本专门将文件锁定1分钟?

[英]How to Lock a file exclusively for 1 minute using windows batch script?

I have a need to lock a file exclusively and continuously keep writing content to it on windows 7. Objective: While the file is being written with an exclusive lock there is a SFTP schedule that pulls this file from a different server. 我需要独占锁定文件,并持续在Windows 7上向其写入内容。目标:当用独占锁定写入文件时,有一个SFTP计划可从另一个服务器提取此文件。 We need to verify if the file is being pulled partially even if there is a Exclusive Lock on the file. 即使文件上有“排他锁”,我们也需要验证文件是否被部分拉出。 Used the below batch script but how do i get a lock for 30 seconds to 1 minute? 使用以下批处理脚本,但是如何获得30秒到1分钟的锁定?

@echo off
if '%1' == '-lock' (
    shift
    goto :main
)
call %0 -lock > SAMPLEFILE.csv
goto :eof
:main
ping -n 30 127.0.0.1 > nul
echo %DATE% %TIME% - start
TREE C:\
echo %DATE% %TIME% - finish
goto :eof

There is an exclusive write lock on SAMPLEFILE.csv for the lifetime of the :main routine. :main例程的整个生命周期中,SAMPLEFILE.csv上具有排他的写锁定。 The lock is released once the :main routine returns. :main例程返回后,将释放锁定。 You can extend the length of the lock by adding a command to delay the return. 您可以通过添加命令延迟返回来延长锁的长度。 For example, timeout 60 /nobreak >nul would delay release of the lock by 1 minute. 例如, timeout 60 /nobreak >nul将使锁定释放延迟1分钟。 But I don't see how that does you any good. 但是我看不出你有什么好处。

The lock only prevents other processes from writing to the file. 该锁仅阻止其他进程写入文件。 Any process can still read the partial file while it is locked. 任何进程都可以在锁定部分文件的同时读取它。 It is possible to detect if a file is locked by another process , but I don't think that will help with your SFTP server. 可以检测文件是否被另一个进程锁定 ,但是我认为这对您的SFTP服务器没有帮助。

I think the simplest thing to prevent partial downloads of the file is to create the file in a folder that the SFTP account(s) cannot access, but on the same volume. 我认为防止文件的部分下载的最简单方法是在SFTP帐户无法访问但位于相同卷上的文件夹中创建文件。 When the file is complete, you can instantly move it to the correct location via the MOVE command. 文件完成后,您可以立即通过MOVE命令将其移至正确的位置。 The file will be invisible to SFTP until the MOVE is complete, so there would be no risk of partial downloads. 在完成MOVE之前,该文件对SFTP是不可见的,因此不会存在部分下载的风险。 Note that this is only instantaneous if moving between two folders within the same volume. 请注意,只有在同一卷中的两个文件夹之间移动时,这才是瞬时的。

By the way, there is no need for your script to call itself with a -lock argument. 顺便说一句,您的脚本不需要使用-lock参数调用自身。 You can get the same effect by calling :main directly. 您可以通过直接调用:main来获得相同的效果。

@echo off
call :main %* >SAMPLEFILE.csv
exit /b

:main
ping -n 30 127.0.0.1 > nul
echo %DATE% %TIME% - start
TREE C:\
echo %DATE% %TIME% - finish
exit /b

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

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