Preventing+more+than+one+instance

Preventing more than one instance
//Question:// Is it possible to detect if another instance of your JB application is already running and prevent additional instances being opened? //Answer:// You can create "lock file" on disk then program run and delete if it quits. Now you can check if that file exists

On with the gory details: user:AltBas:

> The running program leaves the lock file open - don't CLOSE it until the program closes.

> When a new instance of your program starts it tests for the lock file, and also tries to open it. If it can't open it, then the other instance is running (or boogered). Display a message to switch to or close the other instance, or reboot (which will force the orphaned file to close).

> I used a DOS Basic compiler that used this method, and I had to occasionally reboot.

Pseudo- Code: code Test for lock file if lock file exists then Try to open it if you can open then goto [Normal] else Display message Close Other Instance or Reboot end if else Open/Create lock file end if [Normal]

CLOSE #lock kill LockFile$ END code

> The program won't run on a write-only drive (ie, CD). code format="lb" '*** LockTest.Jb - Test of Open File for Enforcing Single Instance ***

NOMAINWIN dim FL$(5,5)

if right$(DefaultDir$, 1) <> "\" then DefaultDir$ = DefaultDir$ + "\"

PrgName$ = "Lock Test" LockFile$ = DefaultDir$ + "Lock.fil"

'* Test if LockFile exists * '* If it exists, see if we can open it * '* If we can't open it, then an instance is running (or hung) *

OpenLock = TestLock(LockFile$) if OpenLock = 0 then NOTICE PrgName$ + " already running" + chr$(13) +_ "Please switch to or close other program instance." + chr$(13) +_ "If the other instance isn't responding, reboot." + chr$(13) +_ "This instance will now end - Good-bye..." + chr$(13) +_ " - Cruel-Hearted Programmer." END end if

BUTTON #prg.btnClose "Close", [Quit], UL, 20, 20, 45, 30 STATICTEXT #prg "No other instance can run while this lock file is open",_ 5, 60, 450, 30 open PrgName$ + " Window" for window as #prg #prg "trapclose [Quit]"

wait '* LockFile$ is open while program runs *

[Quit] CLOSE #lock kill LockFile$ CLOSE #prg END

FUNCTION FileExist(FName$) FILES "", FName$, FL$ FileExist = val(FL$(0,0)) END FUNCTION

FUNCTION TestLock(FName$) Test = FileExist(FName$) if Test = 1 then on error goto [CantDel] kill FName$ '* Another instance isn't running if we can delete file * end if open FName$ for binary as #lock TestLock = 1 EXIT FUNCTION [CantDel] TestLock = 0 '** print Err$ END FUNCTION code