12.9. Locking file range
ScriptBasic provides another type of file locking. This lock locks a range of a file. You can do it using the statement:
LOCK RANGE #fn FROM start_pos TO end_pos FOR mode
fn is the opened file, start_pos and end_pos are expressions resulting integer values meaning the first and the last position of the locking range in terms of records. The parameter mode is the same as for the file locking mechanism, it can be read, write or release.
Note that the positioning uses the same zero offset numbering as the instruction seek. In other words the first record of a file is position 0.
See the following example:
REM locktest1.bas open "locktest.txt" for output as 1 lock region#1 from 1 to 5 for write for i=1 to 5 print #1, "A" next I print "5 bytes are done\n" for i=1 to 5 print #1, "B" next I print "10 bytes are done first 5 bytes are locked\n" line input a close 1
If you run this code in two different terminal windows one will lock the file range and the other will go on and wait for user input. When you press the key ENTER to go on the program grabbing the lock closes the file and the program in the other terminal windows writes out the text and starts to wait. On the other hand if you start `locktest1.bas' in one terminal window and when it starts to wait for user input you start the following `locktest2.bas' in another window, they do not interfere, because they lock different regions of the file.
REM locktest2.bas open "locktest.txt" for output as 1 lock region#1 from 6 to 10 for write seek#1,6 for i=1 to 5 print #1, "D" next I print "done\n" close 1
This locking method implements advisory locking, and the behavior is the same as in the case of file locking. The interpreter calls the system function fcntl on UNIX systems, and LockFileEx on Windows NT. This results different behavior when programs try to read or write a file region locked by another process.
In other words all programs should behave and lock the file or the region before accessing it.