Unix VM file locking?
David T. Lewis
lewis at mail.msen.com
Sun Jan 27 13:49:10 UTC 2008
On Sat, Jan 26, 2008 at 02:28:11PM +0200, Igor Stasenko wrote:
> You can use flock/fcntl for placing an exclusive lock on file descriptor.
This kind of file locking is implemented in OSProcess, see UnixOSProcessAccessor
category "file locking". For the problem that Andreas describes, you can do this:
OSProcessAccessor emulateWin32FileLocking: true. "dangerous for multiple OS processes"
f1 := FileStream newFileNamed: 'foo.bar'.
OSProcess accessor lockFile: f1 exclusive: true ifFail: [f1 close. self error: 'could not lock file'].
f1 nextPutAll: 'Hello World'.
f2 := FileStream oldFileNamed: 'foo.bar'.
OSProcess accessor lockFile: f2 exclusive: true ifFail: [f2 close. self error: 'could not lock file'].
f2 nextPutAll: 'Oh, noes'.
Look first at the unit tests UnixProcessFileLockTestCase, UnixProcessUnixFileLockingTestCase,
and UnixProcessWin32FileLockingTestCase. These attempt to provide some reasonable
test coverage between cooperating Squeak images by means of #forkSqueak.
For this issue (locking the external file from a single Squeak image), the
Windows file locking semantics give the right behavior. However (and this
is a *big* caveat), the Windows semantics (emulated on Unix) will not work
if you are trying to lock files between multiple OS processes, which is of
course the intent of file locking in the first place, so you should use
this only if you are sure that multiple OS process access is not every going
to be an issue for your application. The default setting is to not use Windows
file lock emulation (OSProcessAccessor emulateWin32FileLocking: false), which
is what you want for the more general case of locking files across multiple
Overall, you should use OSProcess file locking with caution. I have tried
to provide test coverage, but I do not know how much (if at all) anyone is
using this in a production setting, and I can't be certain how well it will
hold up under load. That caveat aside, it should work fine for the sort of
issue described here.
More information about the Squeak-dev