Sign in to follow this  
Followers 0
Guest pierre

mutex UDF

2 posts in this topic

This sample code is handy to prevent two scripts from running at the same time.

You just have to use a unique GUID as parameter to CreateMutex.

Maybe a cleaner version could find it's place into process.au3 ?

#include <constants.au3>

AutoItSetOption ("MustDeclareVars", 1)

Global $hMutex
local $errorlevel
Local $closehandle

if CreateMutex("cad77ff0-5d14-11d9-9669-0800200c9a66", $hMutex) then
;;;; Body of program would go here;;;;
 While 1
     Sleep(5000)
 WEnd
;;;;;;;;
 $errorlevel = 0
else
 $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])
 $hMutex = ""; Prevent OnAutoItExit() from releasing an uncreated mutex

 msgbox($MB_SYSTEMMODAL + $MB_ICONEXCLAMATION + $MB_OK, "Error", "Don't run multiple " & @ScriptName)
 $errorlevel = 1
endif

Exit($errorlevel)



func CreateMutex($mutex, byref $hMutex)
 dim $ERROR_ALREADY_EXISTS = 183
 dim $LastError, $closehandle
 dim $retval

 $hMutex = DllCall("kernel32.dll", "long", "CreateMutexA", "ptr", 0, "int", 1, "str", $mutex)
 $LastError = DllCall("kernel32.dll", "long", "GetLastError")

 if $LastError[0] = $ERROR_ALREADY_EXISTS then
  $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])
  $retval = 0
 else
  $retval = 1
 endif

 return $retval
endfunc


func OnAutoItExit()
 dim $releasemutex, $closehandle

 if IsArray ($hMutex) then
  $releasemutex = DllCall("kernel32.dll", "int", "ReleaseMutex", "long", $hMutex[0])
  $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])
 endif
endfunc

Share this post


Link to post
Share on other sites

Already posted a cleaner version...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0