2

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. 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?

@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
MKII
  • 892
  • 11
  • 36
Kiran
  • 23
  • 4

1 Answers1

0

There is an exclusive write lock on SAMPLEFILE.csv for the lifetime of the :main routine. The lock is released once the :main routine returns. 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. 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.

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. When the file is complete, you can instantly move it to the correct location via the MOVE command. The file will be invisible to SFTP until the MOVE is complete, so there would be no risk of partial downloads. 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. You can get the same effect by calling :main directly.

@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
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Thanks dbenham. Your script worked fine with a exclusive, however like you mentioned, the SFTP process is still able to read partial files. – Kiran Aug 19 '15 at 18:35