Jump to content

Close multiple processes have the same name


DCCD
 Share

Recommended Posts

How to Close multiple processes have the same name, all at once all at the same time?, i know how to do that by using The $PID of the process that was launched, but is there another way. that's all, any help would be appreciated

If $cmdline[0] > 0 Then
    Switch $cmdline[1]
        Case "-a", "start"
            MsgBox(0, "-a", "-a")
        Case "-s", "mail"
            MsgBox(0, "-s", "-s")
        Case "-c", "cb"
            MsgBox(0, "-c", "-c")
        Case "-p", "pe"
            MsgBox(0, "-p", "-p")
        Case Else
            MsgBox(0, "ERROR - No Command Line Paramaters!", "Error! No Command Line Parameters Problem")
    EndSwitch
Else
    Run(@ScriptName & " -a")
    Run(@ScriptName & " -s")
    Run(@ScriptName & " -p")
    Run(@ScriptName & " -c")
EndIf
Link to comment
Share on other sites

How to Close multiple processes have the same name, all at once all at the same time?

ProcessList() in the Help File.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

Technically you won't be able to close them at the same time. Either use ProcessList with the process name and loop through that array, or use a do/until loop using the terminating the process name. Or you could also get the freely available and versatile PSkill. If you pass PSkill the process name, it will close all instances of that process name with one command, although technically it uses a loop (internal to the program). With all examples you must specify the process name (initially with processlist)

;with ProcessList
$List = ProcessList('iexplore.exe')
If @error Then Exit
For $i = 1 To $List[0][0]
    ProcessClose($List[$i][1])
Next

;With Do/Until Loop
Do
    ProcessClose('iexplore.exe')
Until Not ProcessExists('iexplore.exe')

;with Pskill
RunWait('pskill.exe iexplore.exe')

Edited by Varian
Link to comment
Share on other sites

thanks a lot all of you but you know i don't try to kill iexplore.exe or anything else it's just my own script and don't forget my application with parameters, so if i close myfile.exe -a -p -c the Loop will killed before ProcessClose finished.

@jazzyjeff thanks, i mean something like ProcessClose, Exit ..etc

Finally, as I said earlier "i know how to do that by using The $PID of the process that was launched" here's an example and this will work just fine. but I was wondering, is there something shorter

If $cmdline[0] > 0 Then
    Switch $cmdline[1]
        Case "-a", "start"
            While 1
                Sleep(250)
            WEnd
        Case "-s", "mail"
            While 1
                Sleep(250)
            WEnd
        Case "-c", "cb"
            While 1
                Sleep(250)
            WEnd
        Case "-p", "pe"
                If MsgBox(0x4, "Exit", "Exit -a -s -c -p") =  6 Then
                    ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID0", ""))
                    ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID1", ""))
                    ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID3", ""))
                EndIf
        Case Else
            MsgBox(0, "ERROR - No Command Line Paramaters!", "Error! No Command Line Parameters Problem")
    EndSwitch
Else
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID0", Run(@ScriptName & " -a"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID1", Run(@ScriptName & " -s"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID2", Run(@ScriptName & " -p"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID3", Run(@ScriptName & " -c"))
EndIf
Edited by DCCD
Link to comment
Share on other sites

Off the top of my head, I would use WinList and ProcessClose within a loop. You will have to know the process name though.

Something like

While processName in WinList

ProcessClose

ProcessWaitClose (if required)

EndWhile

Edit: You could use other methods for the control of the while loop.

While ProcessExist(processName)

While processName in ProcessList

Sure there are others.

Edited by bo8ster

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

If I understand your situation, you are running multiple instances of your script, differentiating between the types by a command line switch. I modified your script a bit so that you may better understand my interpretation of your script (I added Tooltip Info to say which iteration is running). I also added INI writes in case you run the executible with the switch separately.

Your solution works best because you have more than 2 instances of the program running. If you only had 2 instances running you could use ProcessList() with your script name to get your list...one of the elements in the array would be your current instance (@AutoitPID) and and the other would be the program you want to terminate. I have a script (Turn Monitor Off) which works this way. If I execute the program once, it checks to see if any other instances are running (which they are not) so it turns off the monitor and idles around endlessly. When I want to turn the monitor back on, I run the program again and it checks for other instances of the program. It will find 1 other, so a Flag to run the "turn on monitor" function is set, then I use ProccessList() to go through the found instances and kills the 1 NOT with the current PID (@AutoitPID). In short, it toggles the script...1 instance, turn monitor off and wait; 2 instances, terminate other process and turn monitor back on. Here is that snippet:

HotKeySet('{ESC}', '_Quit')
HotKeySet('{END}', '_Quit')

If @Compiled And _Singleton(@ScriptName, 1) = 0 Then    ;if multiple instances are detected
    $aPList = ProcessList(@ScriptName)
    For $i = 1 To $aPList[0][0]
        If $aPList[$i][1] <> @AutoItPID Then    ;proceed with termination if not the current script
            Do
                ProcessClose($aPList[$i][1])
                Sleep(10)
            Until Not ProcessExists($aPList[$i][1])
        EndIf
    Next
    _Monitor_ON()   ;since multiple instances were found, turn monitor back on
Else    ;no other instances, proceed to turn monitor off
    _Monitor_OFF()
EndIf


Func _Monitor_OFF()
    ;Stuff
EndFunc   ;==>_Monitor_OFF

Func _IdleWaitCommit($Idlesec)
    ;Stuff
EndFunc   ;==>_Monitor_ON

Func _Quit()
    _Monitor_ON()   ;failsafe to turn monitor on before exiting script
    Exit
EndFunc   ;==>_Quit

Since you have multiple instances running you'll need some way of storing the PIDs (your INI file) in order to store your PIDs if you only want to kill some of them.. Now, when you run with the "p" switch to terminate the selected ones, you'll do (as you have already done) look in the INI and get the PIDs so you can terminate the proper ones.

NOTE: If you want to kill all instances except "p" instance (which will gracefully terminate itself after the others are terminated), you can modify my snippet to do that.

Case "-p", "pe"
    If _Singleton(@ScriptName, 1) = 0 Then  ;if multiple instances are detected
        $aPList = ProcessList(@ScriptName)
        For $i = 1 To $aPList[0][0]
            If $aPList[$i][1] <> @AutoItPID Then    ;proceed with termination if not the current script
                Do
                    ProcessClose($aPList[$i][1])
                    Sleep(10)
                Until Not ProcessExists($aPList[$i][1])
            EndIf
        Next
    EndIf

The one question that I have (if you do not plan on killing all instances of your program with the "p" switch) is what happens if you run, for example, the "a" switch more than once. You have only allotted 1 place for the PID for any one switch, so running multiple instances of the same switch will only register the last one that was ran. You have not allowed for that scenario. If your intention is to run only one instance of a switch at one time, I would protect that Case statement with _Singleton().

Let me know (with further explanations) if I have misinterpreted your intentions.

Opt("TrayAutoPause", 0)

If $Cmdline[0] > 0 Then
    Switch $Cmdline[1]
        Case "-a", "start"
            TraySetToolTip("Sart")
            IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID0", @AutoItPID)
            While 1
                Sleep(250)
            WEnd
        Case "-s", "mail"
            TraySetToolTip("Mail")
            IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID1", @AutoItPID)
            While 1
                Sleep(250)
            WEnd
        Case "-c", "cb"
            TraySetToolTip("CB")
            IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID3", @AutoItPID)
            While 1
                Sleep(250)
            WEnd
        Case "-p", "pe"
            TraySetToolTip("KILL")
            If MsgBox(0x4, "Exit", "Exit -a -s -c -p") = 6 Then
                ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID0", ""))
                ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID1", ""))
                ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID3", ""))
            EndIf
        Case Else
            MsgBox(0, "ERROR - No Command Line Paramaters!", "Error! No Command Line Parameters Problem")
    EndSwitch
Else
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID0", Run(@ScriptName & " -a"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID1", Run(@ScriptName & " -s"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID2", Run(@ScriptName & " -p"))
    IniWrite(@ScriptDir & "\id.ini", "Confirm", "PID3", Run(@ScriptName & " -c"))
EndIf
Edited by Varian
Link to comment
Share on other sites

@Varian, i really appreciate your time and effort, now look at the code. both looks BIG. So, at this point "This post should be closed". Thanks Again

$aPList = ProcessList(@ScriptName)
For $i = 1 To $aPList[0][0]
    If $aPList[$i][1] <> @AutoItPID Then
        Do
            ProcessClose($aPList[$i][1])
        Until Not ProcessExists($aPList[$i][1])
    EndIf
Next

ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID0", ""))
ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID1", ""))
ProcessClose(IniRead(@ScriptDir & "\id.ini", "Confirm", "PID3", ""))
Link to comment
Share on other sites

Sorry Varian, thats one way! :x But another way is to use _WinAPI_GetProcessCommandLine() which is in WinAPIEx.au3 it shows the command-line parameters of the executed process, therefore not having to save to an INI File.

This Example creates a 2D Array with 3 Columns [Process Name, PID, Command-Line]

#include <Array.au3>
#include <WinAPIEx.au3>

Global $ProcessArray = ProcessList(@ScriptName) ; <<<<< Change to Blank to see all Processes!
If Not $ProcessArray[0][0] = 0 Then ReDim $ProcessArray[$ProcessArray[0][0] + 1][3]
For $A = 1 To $ProcessArray[0][0]
    $ProcessArray[$A][2] = _WinAPI_GetProcessCommandLine($ProcessArray[$A][1])
Next

If IsArray($ProcessArray) Then _ArrayDisplay($ProcessArray, '_WinAPI_GetProcessCommandLine')

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

Sorry Varian, thats one way! :x But another way is to use _WinAPI_GetProcessCommandLine() which is in WinAPIEx.au3 it shows the command-line parameters of the executed process, therefore not having to save to an INI File.

That is VERY handy indeed! I will better acquaint myself with WinAPI calls, as I see that it is extremely useful. Be prepared to answer my questions, guinness:P
Link to comment
Share on other sites

That is VERY handy indeed! I will better acquaint myself with WinAPI calls, as I see that it is extremely useful. Be prepared to answer my questions, guinness

Oh No! You know more about AutoIt than I do, I have read your posts and you always produce interesting code for difficult situations. Plus, WinAPIEx.au3 is essential in my opinion :x

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

Oh No! You know more about AutoIt than I do, I have read your posts and you always produce interesting code for difficult situations. Plus, WinAPIEx.au3 is essential in my opinion :x

Too late!! I already got your name badge ready!:P
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...