Set/GetEnv

BlitzPlus Forums/BlitzPlus Programming/Set/GetEnv

Eikon(Posted 2004) [#1]
Ive been experimenting with SetEnv and GetEnv to detect multiple instances of my program, I got the idea from Snarty. The problem is i've followed his code exactly and it doesnt seem to work.

tmp% = GetEnv("im_running")
Notify tmp%
If tmp% = 1 Then End

SetEnv "im_running", "1"

Graphics 320, 240, 16, 2
SetBuffer BackBuffer()
While Not KeyDown(1)

Flip
Wend

SetEnv "im_running", "0"
End

Compile that in B+ and run the exe twice. The first one should run and set the flag to 1, the second should read the one and end. For me it always returns 0. Can anyone help?


soja(Posted 2004) [#2]
It seems the global environment variables are copied into their own "local" instance each time you run the program. For example, just run the program, then run CMD, and type "set i". There is no "im_running", because it's local to your program instance.

Anyway, there is a much better way to do what you want. Use a Mutex. Here is an example:
; .lib "kernel32.dll"
; CreateMutex%(lpMutexAttributes%,bInitialOwner%,lpName$):"CreateMutexA" 
; GetLastError%():"GetLastError"

Const ERROR_ALREADY_EXISTS=183

CreateMutex(0,1,"My Program Instance") ; Mutex accessible to any program

If GetLastError() = ERROR_ALREADY_EXISTS Then
	Notify "My program is already running" ; Shutdown
Else
	Notify "This is the only instance of My Program" ; OK
EndIf



Eikon(Posted 2004) [#3]
You seem to gravitate to these kind of topics, soja. I predicted you'd come up with something. Thanks for the help, and dont forget to ReleaseMutex ;)


soja(Posted 2004) [#4]
Oh no, I'm predictable!!

I guess I like BlitzPlus... (is that the "kind" you mean?)

=)