How do I hold a file open (locked) from a Windows command-line shell script?

穿精又带淫゛_ 提交于 2019-12-24 17:27:30

问题


I have been reading this thread about detecting a locked file, and now I would like to implement it in my scripts, so I will need a way to programatically detect it in Windows shell scripting.
The accepted solution gives a way to hold a file open/locked:

    (
      >&2 pause
    ) >> test.txt

but this solution needs a key pressing.
I would like to create a Windows shell script similar, like this:

[Create and locking of c:\Temp\ProgramRunning.lck]
--------------- Rest of the Script ---------------
[Blah blah blah]
---------- End of the Main Body the Script ----------
[Unlocking and deletion of c:\Temp\ProgramRunning.lck]

So, when the scripts finishes, the lock file gets deleted (and unlocked, of course). If this script gets stopped, Ctrl+C, window closed, hanging of the system or whatever, the lockfile is not deleted, but is unlocked.

How could I do that?


回答1:


You can use call combined with output redirection to hold a file open until the call returns:

call :main 3>myopenfile.txt
goto :eof

:main
rem do whatever here
goto :eof

If needed, you can write to the file from within the call like this:

>>&3 echo hi


来源:https://stackoverflow.com/questions/22597647/how-do-i-hold-a-file-open-locked-from-a-windows-command-line-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!