how to terminate a process?

Miscellaneous Forums/Win32 Discussion/how to terminate a process?

From your own app...


; ------------------------------------------------------------------------------
; Create kernel32.decls in Blitz/userlibs or add to existing one (remove ; from 3 lines below)...
; ------------------------------------------------------------------------------
; OpenProcess% (access, handleinherit, processid)
; TerminateProcess% (processhandle, exitcode)
; CloseHandle% (Object)
; ------------------------------------------------------------------------------

Const PROCESS_TERMINATE = $1
Const PROCESS_CREATE_THREAD = $2
Const PROCESS_VM_OPERATION = $8
Const PROCESS_VM_READ = $10
Const PROCESS_VM_WRITE = $20
Const PROCESS_DUP_HANDLE = $40
Const PROCESS_CREATE_PROCESS = $80
Const PROCESS_SET_QUOTA = $100
Const PROCESS_SET_INFORMATION = $200
Const PROCESS_QUERY_INFORMATION = $400
Const SYNCHRONIZE = 1048576
Const STANDARD_RIGHTS_REQUIRED = 983040
Const PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or $FFF

; This appears to be pretty much how Windows kills a program if you 'End Process'
; from the Task Manager. Note that this is 'unfriendly'!

Function KillProcess (pid)
    phandle = OpenProcess (PROCESS_TERMINATE, False, pid)
    If phandle <> 0
        If TerminateProcess (phandle, 1)
            result = 1
        EndIf
        CloseHandle (phandle)
    EndIf
    Return result
End Function

; ------------------------------------------------------------------------------
; D E M O . . .
; ------------------------------------------------------------------------------
; Enter process ID here! I suggest going to Task Manager,
; making sure PIDs are shown (try View menu -> Select columns if
; they are not listed), then run a program and enter its number here...
; ------------------------------------------------------------------------------

DebugLog KillProcess (-1) ; Change to process ID you want to kill.


To test it, I'd suggest running a program specifically to be killed. Use the Task Manager to get its 'process ID' and enter that in the KillProcess parameters of the above demo...

The code archive example below will get a list of running processes too, showing which processes have spawned others. You can get other information such as the process ID -- see the PrintProc function. Ugly but it does the job!

Process Tree

Use at your own risk!