2

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?

Community
  • 1
  • 1
Sopalajo de Arrierez
  • 3,543
  • 4
  • 34
  • 52

1 Answers1

3

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
Harry Johnston
  • 35,639
  • 6
  • 68
  • 158