file locking

Started by eddier, December 20, 2002, 10:39:25 AM

Previous topic - Next topic

eddier

Any way to do file locking?



Eddie

Lutz

#1
No filelocking :(, just roll your own filebased semaphore stuff. Unfortunately semaphore functions are not available on the Borland Win32 compiler and neither on the CYGWIN compiler. So that would be a feature for UNIX like systems only.



I had a similar need when I implemented comment counting on the newLISP Blog program, but found a way to keep the counter updated correctly even in multiuser situations. On web apps you also have the problem that an internet connected client might die away and leave your filelock/semaphore in a locked state, so when you work with semaphores you also have to implement some time-to-live counter.



Lutz

CaveGuy

#2
What level of file locking are you looking for ?



If you need the file lock to span secessions,

task A reads and locks file, then task B unlocks

file after it is done, keeping all other tasks locked out

between the two secessions.



or



Task A locks file ... makes changes and releases it.

This is much easier, and far less likely to leave a file

hung.
Bob the Caveguy aka Lord High Fixer.

Lutz

#3
As a lock you could just use the existence of a file semaphore and use the file primitive to check the existense:



App A:



(while (file? "lock")  (sleep 100))

(write-file "lock" "lock semaphore")

(do-a-stuff)

(delete-file "lock")



App B:



(while (file? "lock")  (sleep 100))

(write-file "lock" "lock semaphore")

(do-b-stuff)

(delete-file "lock")



This would be for the second type of file locking.



Lutz

CaveGuy

#4
I did a quick test and determined that the (rename-file function will fail, if the file has been opened for update by a previous task. Someone shoule check the Linux version for consistancy.



Renameing the origional file to a backup name, prior to exclusive access, and then either renameing or copying  the file back to the origional name, releases it for access again, works too....
Bob the Caveguy aka Lord High Fixer.

Lutz

#5
That is correct behavior, one is not be able to rename a file while it is open. Close the file first, than it can be renamed. But using renaming for 'locking' sounds like a good idea, just doit before opening it. The name is the semaphore :)