[Gambas-user] How to lock a file
Benoit Minisini
gambas at ...1...
Tue Oct 7 11:19:24 CEST 2008
On mardi 07 octobre 2008, Rolf-Werner Eilert wrote:
> For my apps in Gambas, I use lockfiles, not folders, to lock a certain
> file. Experience told me that "sometimes" when two users/processes want
> to access the same file, these may overlap. So I added an identification
> method and a time delay in case of locks. This is what it looks like
> (kinda prototyped):
>
> WHILE Exist(theLockFile) THEN
>
> OPEN theLockFile FOR READ ...
> LINE INPUT firstLine
> CLOSE ...
>
> IF firstLine = myOwnName THEN 'old lock file from myself:
> KILL theLockFile 'may be deleted, then proceed
>
> ELSE 'lock file from someone else:
> WAIT one second
>
> WEND
>
> 'now first of all, write my own lockfile
> 'then begin reading the file I want
> 'finally delete lockfile
>
> This is how this looks in practice:
>
> WHILE Exist(pfad &/ "klassenbuch.block")
> OPEN pfad &/ "klassenbuch.block" FOR READ AS #dtnr
> LINE INPUT #dtnr, t$
> CLOSE #dtnr
> IF t$ = system.User THEN
> KILL pfad &/ "klassenbuch.block"
> ELSE
> WAIT 1
> END IF
> WEND
>
>
> OPEN pfad &/ "klassenbuch.block" FOR WRITE CREATE DIRECT AS #dtnr
> PRINT #dtnr, system.User
> CLOSE #dtnr
>
> OPEN karteiVerz &/ jg &/ "klassenbuch" FOR READ AS #dtnr
>
> and so on. While I am writing this email, I find that this has one big
> drawback: If the lock file was made by someone else and that app
> crashed, my program will wait forever for the lockfile to disappear. So
> one should add a counter, e. g. 5 seconds, to stop waiting.
>
> Regards
>
> Rolf
>
So, use the LOCK instruction to create a system-wide mutually exclusive code
section!
--
Benoit Minisini
More information about the User
mailing list