You are confused or misremembering code, or else the code was incorrect.
Redirecting stdin to a file does not lock the file. Any number of process can read from the same file. In addition, one other process could write to the file while it is open for reading.
If you want to lock a file in batch then you want to redirect output to the file.
If you don't care about existing content, then you can use >lock.txt
. If you want to preserve existing content then >>lock.txt
.
The file will be exclusively locked for the duration of the associated command. While locked, no other process can write to the file (redirected output to that file will fail for other processes). But any number of processes can still read from the file while it is locked.
For a simple test, issue pause >lock.txt
from one console window. The lock.txt file will remain locked until you press a key in that window. Now from another console window attempt to write to the file with any command that you like - it will fail. For example echo hello >lock.txt
will fail.
But you can still read from the file while it is locked. For example, type lock.txt
will output Press any key to continue...
.
It is possible for a locked file to function as a queue or messaging service, in which case it might make sense to also have code that uses <lock.txt
.
Here are some links discussing applications of file locking in batch:
How do you have shared log files under Windows?
Parallel execution of shell processes
How to check in command-line if a given file or directory is locked (used by any process)?