Exit

_SingleScript() Assure that only one script with the same name is running

7 posts in this topic

#1 ·  Posted (edited)

 

_SingleScript UDF

 

Close all executing scripts with the same name and continue.

or

Wait for completion of predecessor scripts with the same name.

or

Exit if other scripts with the same name are executing.

or

Test, if other scripts with the same name are executing.
 

#include-once
;==============================================================================================================
; UDF Name:         _SingleScript.au3
; Description:
;               iMode=0  Close all executing scripts with the same name and continue.
;               iMode=1  Wait for completion of predecessor scripts with the same name.
;               iMode=2  Exit if other scripts with the same name are executing.
;               iMode=3  Test, if other scripts with the same name are executing.
;
; Syntax:           _SingleScript([iMode=0])
;                   Default:  iMode=0
; Parameter(s):         iMode:     0/1/2/3    see above
; Requirement(s):       none
; Return Value(s):      -1= error     @error=-1   invalid iMode
;               0= no other script executing @error=0 @extended=0
;               1= other script executing @error=0 @extended=1 (only iMode=3)
; Example:
;               #include "_SingleScript.au3"   ; http://h--e.de/autoit/UDF/_SingleScript.html
;               _SingleScript() ; Close mode ( iMode defaults to 0 )
;               MsgBox(Default, Default, "No other script with name " & StringTrimRight(@ScriptName, 4) & " is executing.", 0)
;               
;           see other example at end of this UDF
;
; Author:           Exit   ( http://www.autoitscript.com/forum/user/45639-exit )
; COPYLEFT:     © 2013 Freeware by "Exit"
;           ALL WRONGS RESERVED
;==============================================================================================================

Func _SingleScript($iMode = 0)
    Local $oWMI, $oProcess, $oProcesses, $aHandle, $aError, $sMutexName = "_SingleScript " & StringTrimRight(@ScriptName, 4)
    If $iMode < 0 Or $iMode > 3 Then Return SetError(-1, -1, -1)
    If $iMode = 0 Or $iMode = 3 Then ; (iMode = 0) close all other scripts with the same name.  (iMode = 3) check, if others are running.
        $oWMI = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
        If @error Then
            RunWait(@ComSpec & ' /c net start winmgmt  ', '', @SW_HIDE)
            RunWait(@ComSpec & ' /c net continue winmgmt  ', '', @SW_HIDE)
            $oWMI = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
        EndIf
        $oProcesses = $oWMI.ExecQuery("SELECT * FROM Win32_Process", "WQL", 0x30)
        For $oProcess In $oProcesses
            If $oProcess.ProcessId = @AutoItPID Then ContinueLoop
            If Not ($oProcess.Name = StringTrimRight(@ScriptName, 4) & ".EXE" Or ($oProcess.Name = "AutoIt3.exe" And StringInStr($oProcess.CommandLine, StringTrimRight(@ScriptName, 4) & ".au3"))) Then ContinueLoop
            If $iMode = 3 Then Return SetError(0, 1, 1) ; indicate other script is running. Return value and @extended set to 1.
            If ProcessClose($oProcess.ProcessId) Then ContinueLoop
            MsgBox(262144, "Debug " & @ScriptName, "Error: " & @error & " Extended: " & @extended & @LF & "Processclose error: " & $oProcess.Name & @LF & "******", 0)
        Next
        Sleep(100) ; allow process to terminate
    EndIf

    $aHandle = DllCall("kernel32.dll", "handle", "CreateMutexW", "struct*", 0, "bool", 1, "wstr", $sMutexName) ; try to create Mutex
    $aError = DllCall("kernel32.dll", "dword", "GetLastError") ; retrieve last error
    If Not $aError[0] Then Return SetError(0, 0, 0)
    If $iMode = "2" Then Exit 1
    If $iMode = "0" Then Return SetError(1, 0, 1) ; should not occur
    DllCall("kernel32.dll", "dword", "WaitForSingleObject", "handle", $aHandle[0], "dword", -1) ; infinite wait for lock
    Return SetError(0, 0, 0)
EndFunc   ;==>_SingleScript

#comments-start     Here is the other example. Uncomment and use TIDY to reformat.
    #include "_SingleScript.au3"  ; http://h--e.de/autoit/UDF/_SingleScript.html
    If $cmdline[0] = 0 Then ; submit all scripts
    TraySetToolTip("No Case")
    _SingleScript() ; Kill other scripts, if others are executing
    For $i = 0 To 7
    Sleep(100)
    ShellExecute(@ScriptFullPath, $i)
    Next
    Exit MsgBox(64 + 262144, Default, "All scripts submitted. See icons in system tray. Case 1 already disappeared.", 0)
    EndIf
    TraySetToolTip("Case " & $cmdline[1])
    Switch $cmdline[1]
    Case 0
    $rc = _SingleScript(3) ; Check, if others are executing
    MsgBox(64 + 262144, Default, "Case " & $cmdline[1] & " executing. " & ($rc ? "Some" : "No") & " other scripts executing.", 0)
    Case 1
    _SingleScript(2) ; Kill this scropt, if others are executing
    Beep(440, 3000) ; you will NOT hear the long beep.
    Case 2, 3, 4, 6, 7
    _SingleScript(1) ; Wait for predecessors completed
    MsgBox(64 + 262144, Default, "Case " & $cmdline[1] & " executing.", 0)
    Case 5
    _SingleScript(1) ; Wait for predecessors completed (case 1-4)
    MsgBox(64 + 262144, Default, "Case " & $cmdline[1] & " executing." & @CRLF & "Now killing other scripts. See icons in system tray.", 0)
    _SingleScript() ; Now kill other scripts. Should be case 6 and 7
    _SingleScript(3) ; Check, if others are executing
    MsgBox(64 + 262144, Default, "Case " & $cmdline[1] & " executing. " & (@extended ? "Some" : "No") & " other scripts executing.", 0)
    EndSwitch
#comments-end

 

Edited by Exit
included source of UDF ; http://h--e.de/autoit/UDF/_SingleScript.html
1 person likes this

My UDFs, Abbrevs and Snippets
If you like my post, just click the like button :) 

Share this post


Link to post
Share on other sites



What if a user just renames the executable to get around the "one process rule"? I have code out there which takes this into account.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

 

_SingleScript UDF

 

Close all executing scripts with the same name and continue.

or

Wait for completion of predecessor scripts with the same name.

or

Exit if other scripts with the same name are executing.

or

Test, if other scripts with the same name are executing.

Excellent.

1 person likes this

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Very good!

If I remember correctly, guinness also wrote some code, for when a program is already running, but minimized and forgotten, so that when you try to start it again, rather than create another instance or fail, it brings the first instance to the fore again.

I've also created code to have it query closure of the first instance instead of fail, and have the second instance as replacement.

Could be good to add them to your UDF, along with the internal ID to avoid the issue guinness mentioned.


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Share this post


Link to post
Share on other sites

If I remember correctly, guinness also wrote some code, for when a program is already running, but minimized and forgotten, so that when you try to start it again, rather than create another instance or fail, it brings the first instance to the fore again.

https://www.autoitscript.com/forum/topic/146672-_singletonhwid-enforce-a-design-paradigm-where-only-one-instance-of-the-script-may-be-running-with-using-a-unique-id-based-on-the-users-hardware/?page=3 (towards the end)

1 person likes this

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites
COPYLEFT:     © 2013 Freeware by "Exit"
            ALL WRONGS RESERVED

:muttley:

1 person likes this

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

As I was updating my code today for similar, as mentioned, I thought I would share it here.


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

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