file locking

For the Compleat Fan
Locked
eddier
Posts: 289
Joined: Mon Oct 07, 2002 2:48 pm
Location: Blue Mountain College, MS US

file locking

Post by eddier »

Any way to do file locking?

Eddie

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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
Posts: 112
Joined: Sun Oct 13, 2002 3:00 pm
Location: Columbus Ohio
Contact:

Post by CaveGuy »

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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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
Posts: 112
Joined: Sun Oct 13, 2002 3:00 pm
Location: Columbus Ohio
Contact:

Post by CaveGuy »

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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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 :)

Locked